内存中的 Swift 数组实例

标签 swift automatic-ref-counting

现在我正在观看 WWDC,了解 Swift 性能 session

在那次 session 中,一张图片让我感到困惑

enter image description here

我知道数组无法在编译时确定其大小,因此它们将项目实例存储在堆中,并将该项目的引用存储在堆栈中,如上所示 (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/

相关文章:

objective-c - 如何避免 xcode 4.5 w/o ARC 出现僵尸错误?

swift - 在 Series 4 上访问苹果跌落检测

ios - "res"代表什么?

cocoa - 截断标签的开头

ios - 如何动态改变按钮的背景

iphone - 自动引用计数 (ARC) 中的 NSThreads

ios - ARC 应用程序可以在 iOS 3.2 上运行吗?

swift - 将文本从 MKMarkerAnnotation 传递到不同的 View Controller

ios - Objective-C ARC block __strong __weak

ios - 尝试将非 ARC 'CallHandler'(调用拦截器)转换为 ARK 遇到问题