如果我想检查变量是否符合协议,有两种方法可以做到:
protocol Computer { }
struct Mac: Computer { }
let device = Mac()
device is Computer // option 1
(device as? Computer) != nil // option 2
从纯性能POV中看,哪个选项更快,多少?假设我们不需要只想知道它是否符合要求的强制转换值。我想第一个选择会更快,但这只是一个猜测。
答案 0 :(得分:1)
我只是做了一个快速测试,所以性能差异是疏忽大意的。这不是测试的理想方法,但是我使用了以下游乐场代码:
import Cocoa
func executionTimeInterval(block: () -> Void) -> CFTimeInterval {
let start = CACurrentMediaTime()
block()
return CACurrentMediaTime() - start
}
protocol Computer {}
struct Mac: Computer {}
// Mark as `Any` in case the compiler optimises the fact that the checks will always be true
let device: Any = Mac()
let iterations = 10000
var cumulativeTime = CFTimeInterval(0)
for _ in 0..<iterations {
cumulativeTime += executionTimeInterval {
_ = device is Computer
}
}
cumulativeTime / CFTimeInterval(iterations) // option1
cumulativeTime = 0
for _ in 0..<iterations {
cumulativeTime += executionTimeInterval {
_ = (device as? Computer) != nil
}
}
cumulativeTime / CFTimeInterval(iterations) // option2