Skip to content

Commit f1160b7

Browse files
committed
Base64: Speedup encoding fix 3
- Use String(unsafeUninitializedCapacity:) instead of String(decoding:as:). - This eliminates an excess String allocation and copy as the decoding of the input string to the result is eliminated.
1 parent 84f581d commit f1160b7

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

Sources/Foundation/NSData.swift

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -600,12 +600,13 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
600600
if dataLength == 0 { return "" }
601601

602602
let capacity = estimateBase64Size(length: dataLength)
603-
let ptr = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: 4)
604-
defer { ptr.deallocate() }
605-
let buffer = UnsafeMutableRawBufferPointer(start: ptr, count: capacity)
606-
let length = NSData.base64EncodeBytes(self, options: options, buffer: buffer)
603+
let result = String(unsafeUninitializedCapacity: capacity) { bufferPtr in
604+
let outputBuffer = UnsafeMutableRawBufferPointer(bufferPtr)
605+
let length = NSData.base64EncodeBytes(self, options: options, buffer: outputBuffer)
606+
return length
607+
}
607608

608-
return String(decoding: UnsafeRawBufferPointer(start: ptr, count: length), as: Unicode.UTF8.self)
609+
return result
609610
}
610611

611612
/// Creates a Base64, UTF-8 encoded Data from the data object using the given options.

0 commit comments

Comments
 (0)