3.5 · The copy-on-write mechanism

The Types section explains what copy-on-write gives you. This one is about how it works, how to write your own, and how to lose it by accident.

Mental model. A copy-on-write value is a handle to shared storage. Copying the handle is free. The storage is duplicated only when someone writes while sharing it, and isKnownUniquelyReferenced is how the writer finds out.

Building it

Implementing copy-on-write for your own type.

  1. How do you implement copy-on-write for your own struct? 3.5.1 · L3
    Wrap the data in a private final class (the storage) and keep a single reference to it inside your struct. Reading goes straight to the storage. Every mutating…
  2. What exactly does isKnownUniquelyReferenced check, and how do you defeat it by accident? 3.5.2 · L5
    isKnownUniquelyReferenced(&ref) returns true when the object’s strong count is exactly one. Weak and unowned references are ignored. It takes the variable…

In the standard library

What Array really is, and the ways it silently copies.

  1. What is an Array in memory, and what is special about the empty array? 3.5.3 · L5
    An Array value is a single pointer to a heap buffer object, so MemoryLayout<[Int]>.size is 8 bytes however many elements it holds. The buffer starts with a…
  2. Why does a mutation sometimes copy the whole array, and how do you prove it? 3.5.4 · L3
    An array mutation copies only if its buffer is shared at that moment. The usual causes: another variable still holds the same array (you assigned it, or are…

More in Memory, ARC & runtime