Created
June 12, 2022 21:34
-
-
Save robertmryan/1127027ca74414a792519eede0fab576 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func benchmark() { | |
let string = String(repeating: "This is it. ", count: 10000) | |
let i1 = 19000 | |
let i2 = 19020 | |
// time computation | |
func tc(computation: (Int, Int) -> Void) { | |
let startTime = DispatchTime.now() | |
for i in 0..<100 { | |
computation(i1 + i, i2 + i) | |
} | |
let endTime = DispatchTime.now() | |
let ns = (endTime.uptimeNanoseconds - startTime.uptimeNanoseconds) | |
print("Time: \(ns)") | |
} | |
tc { (s1, s2) in | |
let start = string.index(string.startIndex, offsetBy: s1) | |
let end = string.index(start, offsetBy: s2 - s1) | |
string[start..<end] | |
} | |
// Time: 23,571,282 | |
tc { (s1, s2) in | |
(string as NSString).substring(with: NSRange(s1..<s2)) | |
} | |
// Time: 646,777 | |
tc { (s1, s2) in | |
let start = string.utf16.index(string.startIndex, offsetBy: s1) | |
let end = string.utf16.index(start, offsetBy: s2 - s1) | |
string[start..<end] | |
} | |
// Time: 31,606 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That having been said, I would
XCTest
with itsmeasure
command, that repeats it ten times;E.g.
That yields:
I.e.
Now that result is less compelling (rather than an order of magnitude faster, it is only 37% faster), but that is going to be skewed because we’re benchmarking not only the substring logic, but also the retrieval of the count and performance of the comparison (i.e. the substring logic is not the only thing being benchmarked). But this is a safer test, to make sure that the compiler is not optimizing any code out of the test.