let nsString = NSString("Some string")
let nsRange = NSRange(5...10)
type(of: nsString.substring(with: nsRange))
// => String.Type
How can I do this, but returning an NSString
instead of a String
. I'm not looking for a solution that uses Range<String.Index>
, I'm aware how to do it that way, but for what i'm doing the speed difference is noticeable. I'd like to keep things in the NSString
world.
Benchmark code:
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]
}
tc { (s1, s2) in
(string as NSString).substring(with: NSRange(s1..<s2))
}
String block
: 55_394_353ns
NSString block
: 1_389_647ns
- 39.86x faster