Code Block var map = [String: String]() let start = Date() for _ in 0..<100000 { var s = "asdf" s = (s as NSString).appendingPathComponent("") s = transform(s) s = (s as NSString).substring(from: 1) map[s] = s } print(-start.timeIntervalSinceNow) func transform(_ s: String) -> String { return "\(s)/\(s)" // return String(format: "%@/%@", s, s) }
On my Mac I get the time interval 0.69 seconds printed out in the console (when using the string interpolation), but when commenting out line 13 and uncommenting line 14 (so that we use String(format:)) I get a 0.33 seconds time interval, less than half the time. Curiously, whenever uncommenting line 5 or line 7, string interpolation is faster.
This took me quite a lot of time to figure out, since I would expect both methods to produce the same kind of string, but string interpolation to be always faster. Does anybody know why?
One uses NSString, and the other uses only pure Swift String.What still doesn't make sense is that the two variants inside the transform() function both use a Swift String, still one is faster to insert into the dictionary than the other.
I wrote:
But it was a little bit inaccurate.(Please remember String(format: "%@/%@", s, s) considered as String(format: "%@/%@", s as NSString, s as NSString).)
Some of the methods in Swift String are just calling the equivalent methods of NSString.
String(format: "%@/%@", s, s) is equivalent to something like NSString(format: "%@/%@", s as NSString, s as NSString) as String.