Skip to content

Commit

Permalink
Ensure Path _str takes UTF-8 String fast paths
Browse files Browse the repository at this point in the history
Some clients (*cough* *cough* Xcode) like to create Paths out of bridged
NSStrings, which cannot be efficiently iterated. As most of our
operations require doing this frequently, we might as well convert on
construction to avoid the -characterAtIndex: slow path.
  • Loading branch information
saagarjha committed Feb 4, 2025
1 parent 8d38668 commit f92f07b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Sources/SWBUtil/Path.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ public struct Path: Serializable, Sendable {
}

public init(_ str: String) {
var str = str
str.makeContiguousUTF8()
self._str = str
}

Expand Down
16 changes: 16 additions & 0 deletions Tests/SWBUtilPerfTests/PathPerfTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
//
//===----------------------------------------------------------------------===//

import Foundation
import Testing
import SWBTestSupport
import SWBUtil
Expand Down Expand Up @@ -142,4 +143,19 @@ fileprivate struct PathPerfTests: PerfTests {
#expect(lengths == (path.str.utf8.count + 1 + path2.str.utf8.count) &* N)
}
}

@Test
func bridgedPerf_X100000() async {
let string = (String(repeating: "/hello/little/world", count: 10) as NSString).standardizingPath
let path = Path(string)
let N = 100_000
await measure {
var lengths = 0
for _ in 0..<N {
let result = path.normalize()
lengths = lengths &+ result.str.utf8.count
}
#expect(lengths == string.utf8.count &* N)
}
}
}

0 comments on commit f92f07b

Please sign in to comment.