使用零合并运算符的快速编译时间 [英] Swift compilation time with nil coalescing operator
问题描述
在阅读了有关快速编译时间的文章之后。我想知道为什么使用两个以上的序列合并运算符会大大增加编译时间。
After reading of the article about swift compiling time. I am interested in why usage of more than 2 sequence coalescing operator increase compilation time significantly.
示例:
编译时间为3.65秒。
Example: Compilation time 3.65 sec.
func fn() -> Int {
let a: Int? = nil
let b: Int? = nil
let c: Int? = nil
return 999 + (a ?? 0) + (b ?? 0) + (c ?? 0)
}
编译时间0.09秒。
func fn() -> Int {
let a: Int? = nil
let b: Int? = nil
let c: Int? = nil
var res: Int = 999
if let a = a {
res += a
}
if let b = b {
res += b
}
if let c = c {
res += c
}
return res
}
推荐答案
我几乎可以肯定这与类型推断有关。在解释所有这些 +
和 ??
运算符时,编译器在后台进行了大量工作以推断出这些参数的类型。仅 +
运算符就有大约30个重载,当将其中的几个链接在一起时,会使编译器的工作比您想象的要复杂得多。
I'm almost certain that this has to do with type inference. When interpreting all of those +
and ??
operators the compiler is doing a lot of work behind the scenes to infer the types of those arguments. There are around thirty overloads for the +
operator alone and when you chain several of them together you are making the compiler's job much more complicated than you might think.
这篇关于使用零合并运算符的快速编译时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!