Created
January 8, 2016 20:19
-
-
Save zwaldowski/5f1a1011ea368e1c833e to your computer and use it in GitHub Desktop.
String initialization notes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The gold standard, at least at present | |
let utf8Buffer: UnsafeBufferPointer<CChar> = ... | |
var arrayVersion = Array(utf8Buffer) | |
arrayVersion.append(0) | |
let string = String.fromCString(arrayVersion) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let utf8Buffer: UnsafeBufferPointer<UInt8> = ... | |
// Crossing the NSString bridge performs slower than you'd like | |
let nsString1 = NSString(bytes: utf8Buffer.baseAddress, length: utf8Buffer.count, encoding: NSUTF8StringEncoding)! | |
let string1 = string1 as String | |
// The bridged initializer does an Array() memoization, so it's even slower | |
let string2 = String(bytes: utf8Buffer, encoding: NSUTF8StringEncoding)! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let utf8Buffer: UnsafeBufferPointer<UInt8> = ... | |
let codePointCount = ... // assume this comes from UTF16.measure(_:input:repairIllFormedSequences:) and we're isAscii | |
// The slowest of all, unforunately, even if you make the same isAscii optimization as _StringBuffer.fromCodeUnits(_:input:repairIllFormedSequences:minimumCapacity:). | |
var string1 = "" | |
string1.reserveCapacity(codePointCount) | |
transcode(UTF8.self, UTF16.self, utf8Buffer.generate(), { | |
string1.append($0) | |
}, stopOnError: true) | |
// alternatively, this is ridiculously faster (50% better than fromCString) | |
let string2 = unsafeBitCast(_StringCore(baseAddress: utf8Buffer.baseAddress, count: utf8Buffer.count, elementShift: 0, hasCocoaBuffer: false, owner: nil), String.self) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment