现在我正在观看 WWDC,了解 Swift 性能 session
在那次 session 中,一张图片让我感到困惑
我知道数组无法在编译时确定其大小,因此它们将项目实例存储在堆中,并将该项目的引用存储在堆栈中,如上所示 (d[0]
, d[ 1]
)
但是该数组中的 refCount
是什么(d[0]
旁边)?
drawables
是数组实例的变量指针吗?
最佳答案
数组是一种结构
,因此是一种值类型。但是,存在一些写时复制优化,这可能是此 refCount
的原因。
在 documentation for Array ,它指出:
Arrays, like all variable-size collections in the standard library, use copy-on-write optimization. Multiple copies of an array share the same storage until you modify one of the copies. When that happens, the array being modified replaces its storage with a uniquely owned copy of itself, which is then modified in place. Optimizations are sometimes applied that can reduce the amount of copying.
它还给出了一个例子:
In the example below, a numbers array is created along with two copies that share the same storage. When the original numbers array is modified, it makes a unique copy of its storage before making the modification. Further modifications to numbers are made in place, while the two copies continue to share the original storage.
var numbers = [1, 2, 3, 4, 5] var firstCopy = numbers var secondCopy = numbers // The storage for 'numbers' is copied here numbers[0] = 100 numbers[1] = 200 numbers[2] = 300 // 'numbers' is [100, 200, 300, 4, 5] // 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5]
所以在数组变异之前,数组的存储是共享的。这就是为什么它需要计算引用,而不是释放仍可能被另一个变量使用的数组。
关于内存中的 Swift 数组实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69045076/