gpt4 book ai didi

swift - 是否有 swiftc 编译器优化来删除不必要的大变量?

转载 作者:行者123 更新时间:2023-11-28 12:13:09 25 4
gpt4 key购买 nike

当我用高阶函数编写代码时,我发现像这样一次编写一个转换的表达式会更清晰:

let children = objects.map { $0.children }
let validChildren = children.filter { $0.isValid }
let sortedChildren = validChildren.sorted { $0.count < $1.count }

但是,我知道这些函数中的每一个都会返回一个新的 Array 对象,我将其存储到一个变量中,因此理论上我每次都会创建并保留一个新的 Array 并浪费大量内存。最好将调用写成一行,以便在使用后销毁不需要的数组。

let sortedChildren = objects.map { $0.children } .filter { $0.isValid } .sorted { $0.count < $1.count }

但稍后阅读起来会更烦人,因为一行代码中发生了太多事情。所以我的问题是:Swift 的编译器是否有优化来原谅我的挑剔并在编译时删除未使用的变量?

最佳答案

@MartinR 在问题评论中提到了这一点,但值得官方回答和来源。

As per the Swift repository docs:

All standard library containers in Swift are value types that use COW (copy-on-write) [4] to perform copies instead of explicit copies. In many cases this allows the compiler to elide unnecessary copies by retaining the container instead of performing a deep copy. This is done by only copying the underlying container if the reference count of the container is greater than 1 and the container is mutated. For instance in the following, no copying will occur when d is assigned to c, but when d undergoes structural mutation by appending 2, d will be copied and then 2 will be appended to d:

var c: [Int] = [ ... ]
var d = c // No copy will occur here.
d.append(2) // A copy *does* occur here.

由于高阶函数不会修改调用它们的对象,因此可以很有把握地说结果针对大小进行了优化。

关于swift - 是否有 swiftc 编译器优化来删除不必要的大变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com