Why is fast character comparison so slow?

I was writing code in swift that involved a lot of character comparisons in words and found it to be very slow. When I checked Tools it said that about 33% of the cpu was taken by the == infix on two characters, so I wrote this to test it:

import Foundation
let numTimes = 1000000

let charA: Character = "a";
let charB: Character = "b";
let stringA: String = "a";
let stringB: String = "b";
let nsStringA: NSString = "a";
let nsStringB: NSString = "b";

var start = NSDate();
for var i = 0; i < numTimes; i++ {
    charA == charB;
}
println("Swift Char Time: \(start.timeIntervalSinceNow * -1)")

start = NSDate();
for var i = 0; i < numTimes; i++ {
    stringA == stringB;
}
println("Swift String Time: \(start.timeIntervalSinceNow * -1)")

start = NSDate();
for var i = 0; i < numTimes; i++ {
    nsStringA == nsStringB;
}
println("NSString Time: \(start.timeIntervalSinceNow * -1)")

      

Result:
Swift Char Time: 2.94823098182678
Swift String Time: 0.413999974727631
NSString Time: 0.228329002857208

Does anyone know why this would be?

+3


source to share


1 answer


I found your question very interesting and I delved deeper into the Swift Documentation, so here is my guess:

Character

type is a Unicode scanner (21-bit number), so when you test charA == charB

, the CPU compares the two Unicode scanners.

String

is a set of Unicode scanners, so when you test stringA == stringB

, the CPU compares the hash of the collection, so it weighs more than a Unicode scanner.



And I found that in the Swift doc : "The Swifts String type easily connects to the NSString Foundation", which might explain the time difference between NSString

and String

.

I'll update the answer to confirm when I have more time to go deeper.

+3


source







All Articles