Copy-on-write and implementing it for a custom struct
value semantics with shared backing storage.
CoW shares a buffer until mutation, deep-copying only when the buffer is non-unique; Array, Dictionary, Set, String use it; implement with a class storage box and isKnownUniquelyReferenced.
WHY IT EXISTS Value semantics promise that copies are independent, but eagerly deep-copying large data on every assignment would be wasteful. Copy-on-write preserves the independent-copy guarantee while deferring the actual copy until it is truly needed.
THE MENTAL MODEL Multiple value copies can point at the same underlying reference-counted buffer. Reads are free. The moment a writer mutates a buffer that has more than one owner, the type clones the buffer first, so the writer mutates a private copy and other owners are unaffected. If the buffer is uniquely owned, the mutation happens in place with no copy.
WHICH STANDARD TYPES USE IT Array, Dictionary, Set, and String all implement copy-on-write, which is why passing or assigning them is cheap until a mutation diverges the copies.
IMPLEMENTING IT FOR A CUSTOM STRUCT Put the real data inside a private final class, the storage box, and have the struct hold a reference to it. Expose value-type API on the struct. Before any mutating method touches the storage, call isKnownUniquelyReferenced on the reference; if it returns false the storage is shared, so create a fresh copy of the box and point at it before mutating. This reproduces the standard-library behavior.
WHEN IT MATTERS For large structs or custom collections passed around frequently, CoW avoids repeated deep copies while keeping safe value semantics. It is also why naive benchmarking of struct copies can mislead.
COMMON WRONG ANSWERS Believing every struct gets CoW automatically; only types built around reference-counted storage do. Using a struct as the storage box, which cannot be reference-counted or shared.
ONE CONCRETE EXAMPLE A custom Matrix struct wraps a private final class holding a flat element array. Two matrices assigned from each other share one storage box. When one calls a mutating set(row:col:value:), the method first checks isKnownUniquelyReferenced; seeing the box shared, it clones the storage, then writes. The other matrix keeps its original data, exactly matching how Array behaves.
Read the original → amitsen.de
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.