Skip to content

Commit 5d81136

Browse files
committed
[c++-interop] Improve performance of creating a C++ std::string from a contiguous UTF-8 Swift.String
1 parent 739c719 commit 5d81136

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

stdlib/public/Cxx/std/String.swift

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,17 @@ extension std.string {
2020
/// - Complexity: O(*n*), where *n* is the number of UTF-8 code units in the
2121
/// Swift string.
2222
public init(_ string: String) {
23-
self.init()
24-
let utf8 = string.utf8
25-
self.reserve(utf8.count)
26-
for char in utf8 {
27-
self.push_back(value_type(bitPattern: char))
23+
if string.isContiguousUTF8 {
24+
self = string.withCString(encodedAs: UTF8.self) { buffer in
25+
Self(buffer, string.utf8.count, .init())
26+
}
27+
} else {
28+
self.init()
29+
let utf8 = string.utf8
30+
self.reserve(utf8.count)
31+
for char in utf8 {
32+
self.push_back(value_type(bitPattern: char))
33+
}
2834
}
2935
}
3036

0 commit comments

Comments
 (0)