Reputation: 2598
Now i’m watching WWDC, Understanding Swift performance session
In that session one picture makes me confusing
I know that array cannot determine it’s size at compile time, so they store item instance in heap, and store that item’s reference in stack like above (d[0]
, d[1]
)
but what is refCount
in that array(next to d[0]
)?
Isdrawables
variable pointer for array instance?
Upvotes: 2
Views: 1325
Reputation: 30341
Arrays are a struct
, therefore a value type. However, there are some copy-on-write optimizations, which may be the reason for this refCount
.
In the documentation for Array, it states:
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.
It also gives an example:
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]
So before the array is mutated, the storage of the array is shared. This is why it needs to count the references, to not deallocate an array which still may be in use by another variable.
Upvotes: 2