与在 swift 中编写函数相比,创建闭包是否会对性能造成性能损失?

Is there a performance penalty for creating a closure vs writing a function in swift?

提问人:serotonino 提问时间:7/27/2023 更新时间:7/28/2023 访问量:57

问:

与普通函数相比,创建和使用闭包是否有性能损失? 请参阅以下示例:

使用闭包:

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
}

哪一个会更快,为什么?
提前致谢?

SWIFT 函数 性能 闭包

评论

1赞 Leo Dabus 7/28/2023
这没什么区别。它们是完全一样的。
0赞 serotonino 8/1/2023
在语法上相同或编译相同?你基于什么?你有什么参考资料可以让我仔细检查吗?

答:

0赞 berbaspin 7/28/2023 #1

没有性能损失,因为全局函数和嵌套函数是闭包的特例。

评论

0赞 serotonino 8/1/2023
谢谢!当然在语法上,但我怀疑编译器对它们的处理方式不同......你有什么来源来支持你的主张吗?
0赞 berbaspin 8/2/2023
@serotonino docs.swift.org/swift-book/documentation/......