[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.
This commit is contained in:
Ian Partridge
2019-04-23 10:43:14 +01:00
parent afc9e20d04
commit 3425f4fb4a

View File

@@ -800,9 +800,14 @@ extension StringProtocol where Index == String.Index {
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
switch encoding {
case .utf8:
return Data(self.utf8)
default:
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
}
// @property NSString* decomposedStringWithCanonicalMapping;