Skip to content

Commit 3425f4f

Browse files
committed
[String] [Foundation] perf: UTF8 String -> Data
Currently, `str.data(using:allowLossyConversion)` always bridges via `NSString`. As `String` is now natively UTF8 we can fastpath this conversion in the case where the user requests UTF8 encoding. A benchmark for this was previously added in #22648.
1 parent afc9e20 commit 3425f4f

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

stdlib/public/Darwin/Foundation/NSStringAPI.swift

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -800,9 +800,14 @@ extension StringProtocol where Index == String.Index {
800800
using encoding: String.Encoding,
801801
allowLossyConversion: Bool = false
802802
) -> Data? {
803-
return _ns.data(
804-
using: encoding.rawValue,
805-
allowLossyConversion: allowLossyConversion)
803+
switch encoding {
804+
case .utf8:
805+
return Data(self.utf8)
806+
default:
807+
return _ns.data(
808+
using: encoding.rawValue,
809+
allowLossyConversion: allowLossyConversion)
810+
}
806811
}
807812

808813
// @property NSString* decomposedStringWithCanonicalMapping;

0 commit comments

Comments
 (0)