[swift-users] Large Structs, and COW.

Dave Abrahams dabrahams at apple.com
Fri Jan 22 17:06:03 CST 2016


on Fri Jan 22 2016, Daniel Tartaglia <swift-users-AT-swift.org> wrote:

> If I have a large struct with lots of sub-structs and I assign to just
> one field of one of the sub-structs, will the system make a deep copy
> of the struct or a shallow copy where the unmodified portions of the
> object still point the same memory as the original struct?
>
> In other words, given this code:
>
> struct SubStruct {
>     var a: Int = 0
>     var b: Int = 0
> }
>
> struct VeryLarge {
>     var subStructA = SubStruct()
>     var subStructB = SubStruct()
>     var subStructC = SubStruct()
>     // lots of other stuff
> }
>
> func bar(var vl: VeryLarge) -> VeryLarge {
>     vl.subStructA.a = 5
>     return vl
> }
>
> let vl1 = VeryLarge()
> let vl2 = bar(vl1)
>
> Will vl2.subStructB be a copy of vl1.subStructB, or an entirely new
> object?

It will be entirely distinct memory, unless SubStruct was explicitly
built to use CoW or consists of parts that were built that way
(e.g. arrays).

> I’m worried about performance when making small changes to large objects.

But that's a different issue, because Swift will in fact make in-place
mutations in most cases.  In the above code you're explicitly saying,
"don't change vl1; make a copy and change that."  If you just say
vl1.subStructA.a = 5, there's normally no reason to worry.

-- 
-Dave



More information about the swift-users mailing list