Skip to content

Instantly share code, notes, and snippets.

@zwaldowski
Created January 8, 2016 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zwaldowski/5f1a1011ea368e1c833e to your computer and use it in GitHub Desktop.
Save zwaldowski/5f1a1011ea368e1c833e to your computer and use it in GitHub Desktop.
String initialization notes
// The gold standard, at least at present
let utf8Buffer: UnsafeBufferPointer<CChar> = ...
var arrayVersion = Array(utf8Buffer)
arrayVersion.append(0)
let string = String.fromCString(arrayVersion)
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)!
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