我在 swift中编写了一些代码,其中包含大量字符比较,发现它非常慢.当我检查了Instruments时,它说大约有33%的cpu被两个字符的infix ==占用,所以我写了这个来测试它: import Foundationlet numTim
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)")
结果:
Swift Char时间:2.94823098182678
Swift String Time:0.413999974727631
NSString时间:0.228329002857208
有谁知道为什么会这样?
我发现你的问题非常有趣,我更深入地了解了Swift文档,所以这是我的假设:字符类型是Unicode标量(21位数字),因此当您测试charA == charB时,CPU正在比较两个Unicode标量.
String是Unicode标量的集合,因此当您测试stringA == stringB时,CPU正在比较集合的哈希码,因此它比Unicode标量更轻量级.
我在Swift doc中发现:“Swift的String类型与Foundation的NSString类无缝桥接”,可以解释NSString和String比较之间的时差.
当我有更多时间深入时,我会更新答案以确认.