提问人:serotonino 提问时间:7/27/2023 更新时间:7/28/2023 访问量:57
与在 swift 中编写函数相比,创建闭包是否会对性能造成性能损失?
Is there a performance penalty for creating a closure vs writing a function in swift?
问:
与普通函数相比,创建和使用闭包是否有性能损失? 请参阅以下示例:
使用闭包:
let array = [1, 2, 3]
let doubler: (Int) -> Int = {
$0 * 2
}
array.map {
doubler($0)
}
使用函数
let array = [1, 2, 3]
array.map { double($0) }
...
func double(_ num: Int) -> Int {
return num * 2
}
哪一个会更快,为什么?
提前致谢?
答:
0赞
berbaspin
7/28/2023
#1
没有性能损失,因为全局函数和嵌套函数是闭包的特例。
评论
0赞
serotonino
8/1/2023
谢谢!当然在语法上,但我怀疑编译器对它们的处理方式不同......你有什么来源来支持你的主张吗?
0赞
berbaspin
8/2/2023
@serotonino docs.swift.org/swift-book/documentation/......
评论