Search code examples
arraysswiftmemorywwdc

How Swift implement Array's copy-on-write behavior?


After watching build better apps with value type . In the photoshop example they made, they said that

the only thing that gets copied in the two instances of that diagram are the tiles that contain the person's shirt. So even though I have two distinct documents, the old state and the new state, the only new data that I have had to consume as a result of that is the tiles contained in this person's shirt.

So I begin to wonder how would these two array in memory looks like. So I do a little experiment.

struct Test {
    var i: Int
    var j: Int
}

var valueArray = [Test(i: 1, j: 9), Test(i: 2, j: 7)]
var valueArray2 = valueArray

When I print valueArray and valueArray2's address, they are not the same.
"Maybe they implement this by store pointer in array?"
But when I print memory content using lldb , they are actually just 4 Int (1,9,2,7).
So I am confused, I haven't even change the array yet. And they seems to make a copy of entire array? So where did I misunderstand?
The function I used to print struct's address is by using the method provided by @nschum in this question.

func address(o: UnsafePointer<Void>) {
    let addr = unsafeBitCast(o, Int.self)
    print(NSString(format: "%p", addr))
}

This is not a duplicate question of this question. I am asking about language feather and the other one is about programming skill.


Solution

  • Okay, I did many experiment and finally figured out.

    1. We can's use & to get array address because once we do that , Swift will copy the array to better interact with C, use & get object's address that adjacent to array and do the math instead. Or use lldb instruction frame variable -L
    2. The whole Array is copied once any of it's value element changed.
    3. Actual value element of Array is allocated at heap.
    4. Swift also did a lot of optimization for Array whose element is class.
    5. Swift is awesome.

    I actually write my first blog for this.