Copy-on-write behaviour of collection types

In docs, it says “Collections defined by the Swift standard library like arrays, dictionaries, and strings use an optimization to reduce the performance cost of copying. Instead of making a copy immediately, these collections share the memory where the elements are stored between the original instance and any copies. If one of the copies of the collection is modified, the elements are copied just before the modification. The behavior you see in your code is always as if a copy took place immediately.”

My question is, does the collection, such as an array, copy over all of its elements the moment a single one gets modified, or does it only copy over the one that’s being modified? Just looking to understand the design and the thinking behind it more.

All of them, which is implied by this:

1 Like

Outside the Standard Library you might also want to look at HashTreeCollections. These are built on CHAMP data structures for structural sharing that can get you log n copy-on-write performance.

2 Likes