Copy-on-write collections
How Array is a value type without copying on every assignment: shared storage, isKnownUniquelyReferenced, a copy-on-write stack and deque, what the first write after a copy costs, accidental copies, and where value semantics stop.
- CS61B
- Swift addition: value semantics for collections
- Swift book
- Structures and Classes · Memory Safety
- Documentation
- isKnownUniquelyReferenced(_:) · Array
This lesson has no CS61B counterpart, because Java has no value-type
collections. It answers a question that Lesson 13 left open. Swift’s arrays
are values: var b = a gives b its own array, and changing b never
changes a. But copying a million-element array on every assignment, every
function call, and every return would make Swift unusably slow. It does not
happen, and the technique that avoids it, copy-on-write, is one you can
use in your own collections.
Sharing until someone writes
An Array value is small: essentially a reference to a heap-allocated
buffer that holds the elements. Assigning an array copies that reference,
not the elements, so two arrays can share a buffer. Only when one of them is
about to be changed does it check whether the buffer is shared, and if
so, copy it first:
let a = Array(1...1000)
var b = a
func sameBuffer(_ x: [Int], _ y: [Int]) -> Bool {
x.withUnsafeBufferPointer { px in
y.withUnsafeBufferPointer { py in px.baseAddress == py.baseAddress }
}
}
print(sameBuffer(a, b)) // true: the assignment copied nothing
b[0] = 99 // b's buffer is shared, so b copies it first
print(sameBuffer(a, b), a[0], b[0]) // false 1 99
withUnsafeBufferPointer exposes the address of an array’s buffer, which
Lesson 30 explained, so we can see the sharing directly. The copy happens
at the last possible moment, and only if it is needed: if a had gone away
before b[0] = 99, b would have been the buffer’s only owner and changed
it in place.
The result is the best of both kinds of type. The semantics are those of a value: no change is ever visible through another variable. The cost is often that of a reference: passing an array to a function, or returning one, copies a pointer.
Is anyone else looking?
The check at the heart of copy-on-write is a standard library function:
isKnownUniquelyReferenced(&object) returns true if the object has exactly
one strong reference, the one being passed. That is ARC’s reference count,
from Lesson 25, put to use.
To build a copy-on-write collection, keep the elements in a private class, and before every mutation make sure the storage is not shared:
var copies = 0
struct Stack<Element> {
private final class Storage {
var items: [Element]
init(_ items: [Element]) {
self.items = items
}
}
private var storage = Storage([])
private mutating func makeUnique() {
if !isKnownUniquelyReferenced(&storage) {
storage = Storage(storage.items)
copies += 1
}
}
mutating func push(_ item: Element) {
makeUnique()
storage.items.append(item)
}
mutating func pop() -> Element? {
makeUnique()
return storage.items.popLast()
}
var top: Element? { storage.items.last }
var count: Int { storage.items.count }
}
var s = Stack<Int>()
for n in 0..<100 {
s.push(n) // storage is unique: no copies
}
var t = s // shares s's storage
t.push(100) // shared: copy once
t.push(101) // unique again: no copy
print(copies, s.top!, t.top!, s.count, t.count) // 1 99 101 100 102
Three rules make it correct:
- Every mutating method calls
makeUnique()before it changes the storage. Forget one, and a change through one value is visible through another: the value semantics are broken. - Reading does not need the check.
topandcountjust read the shared storage. makeUniqueismutatingand passes&storage. The check needs the variable itself, not a copy of the reference, which would add a second reference and make the answer always “not unique”.
What would Swift print?
final class Box {
var value = 0
}
var box = Box()
print(isKnownUniquelyReferenced(&box))
let other = box
print(isKnownUniquelyReferenced(&box))
_ = otherShow answer and explanation
Answertrue
false
At first box is the object’s only reference. After let other = box, there
are two, so the object is shared, and a copy-on-write type would copy before
writing.
This Stack is built on an Array, which already has copy-on-write, so
wrapping it adds nothing in practice. The technique matters when the storage
is something without it: linked nodes, a ring buffer, the raw memory of
Lesson 30. Then the wrapper is what turns a reference-type data structure
into a value type.
A value-type deque
Lesson 29’s LinkedListDeque is a class. Wrapping it gives a deque with the
semantics of Array. The copy walks the ring and builds new nodes, so it
costs time proportional to the length, but it happens only on the first write
after the deque was shared:
final class LinkedListDeque<Element> {
private final class Node {
var item: Element?
var next: Node!
weak var prev: Node!
init(_ item: Element?) { self.item = item }
}
private let sentinel = Node(nil)
private(set) var count = 0
init() {
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit { sentinel.next = nil }
func addLast(_ item: Element) {
let new = Node(item)
new.prev = sentinel.prev
new.next = sentinel
sentinel.prev.next = new
sentinel.prev = new
count += 1
}
func removeFirst() -> Element? {
guard count > 0 else { return nil }
let first = sentinel.next!
sentinel.next = first.next
first.next.prev = sentinel
count -= 1
return first.item
}
var items: [Element] {
var result: [Element] = []
var node = sentinel.next!
while node !== sentinel {
result.append(node.item!)
node = node.next
}
return result
}
func copy() -> LinkedListDeque<Element> {
let copy = LinkedListDeque<Element>()
for item in items {
copy.addLast(item)
}
return copy
}
}
struct Deque<Element> {
private var storage = LinkedListDeque<Element>()
private mutating func makeUnique() {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.copy()
}
}
mutating func addLast(_ item: Element) {
makeUnique()
storage.addLast(item)
}
mutating func removeFirst() -> Element? {
makeUnique()
return storage.removeFirst()
}
var count: Int { storage.count }
var items: [Element] { storage.items }
}
var queue = Deque<String>()
queue.addLast("a")
queue.addLast("b")
let saved = queue // a snapshot, for free
_ = queue.removeFirst() // copies, because saved shares the storage
queue.addLast("c")
print(queue.items, saved.items) // ["b", "c"] ["a", "b"]
saved is a true snapshot. Keeping one costs nothing until the next change,
and then one copy, after which the two go their separate ways. Undo
histories, the previous state of a game, and a value passed to another thread
are all cheap for the same reason.
What copy-on-write costs
The price is that one write after a copy is expensive, where every other write is cheap. For a single variable, this almost never matters. It matters in two situations.
Accidental sharing in a loop. If a reference to the storage is kept alive where you did not intend, every write copies:
var copies = 0
struct Stack {
private final class Storage {
var items: [Int] = []
}
private var storage = Storage()
mutating func push(_ item: Int) {
if !isKnownUniquelyReferenced(&storage) {
let fresh = Storage()
fresh.items = storage.items
storage = fresh
copies += 1
}
storage.items.append(item)
}
}
var stack = Stack()
var history: [Stack] = []
for n in 0..<1_000 {
history.append(stack) // keeps a reference to the current storage
stack.push(n) // so every push copies
}
print(copies) // 1000
Here the snapshots were the point, and a thousand copies of a growing stack was the price. When they are not the point, look for extra variables that still hold the old value.
Big copies at the wrong moment. A copy of a million-element structure takes as long as a million writes. If that happens in a loop that runs once per frame of an animation, the frame is late. When performance matters, measure, and hold only one reference to a collection you are about to change.
Where value semantics stop
Copy-on-write copies the storage, and the storage holds the elements. If the elements are themselves class instances, the copy holds the same references:
What would Swift print?
final class Counter {
var n = 0
}
var a = [Counter(), Counter()]
var b = a
b[0].n = 5
b.append(Counter())
print(a[0].n, a.count, b.count)Show answer and explanation
Answer5 2 3
b[0].n = 5 does not change the array b; it changes the object both arrays
point to, so no copy happens, and a sees it. Appending does change b, which
copies the buffer, so the counts differ. An array of objects is a value
holding references, as Lesson 25’s arrays of walruses were.
A collection has full value semantics only if its elements do. That is one more reason Swift code uses structures for data wherever it can.
Put the lines in order
Put the lines in order so the program prints [1, 2] [1].
print(copy, original)var original = [1]var copy = originalcopy.append(2)
Show the correct program
var original = [1]
var copy = original
copy.append(2)
print(copy, original)Lab 32: Copy-on-write
Q0: What would Swift print?
What would Swift print?
final class Storage {
var items: [Int] = []
}
struct Broken {
var storage = Storage()
mutating func add(_ n: Int) {
storage.items.append(n)
}
}
var x = Broken()
var y = x
y.add(1)
print(x.storage.items, y.storage.items)Show answer and explanation
Answer[1] [1]
A structure that wraps a class without copy-on-write has reference semantics
in disguise: var y = x copies the reference, and add changes the shared
storage. This is exactly the bug makeUnique exists to prevent.
What would Swift print?
var copies = 0
struct Box {
final class Storage {
var value = 0
}
var storage = Storage()
mutating func set(_ v: Int) {
if !isKnownUniquelyReferenced(&storage) {
storage = Storage()
copies += 1
}
storage.value = v
}
}
var a = Box()
var b = a
var c = a
b.set(1)
c.set(2)
a.set(3)
print(copies, a.storage.value, b.storage.value, c.storage.value)Show answer and explanation
Answer2 3 1 2
Three values share one storage. b.set copies (three owners). c.set copies
too: a and c still shared the original. By the time a.set runs, a is
the original’s only owner, so it writes in place. (This Box copies without
carrying the old value over, which is fine here since set replaces it.)
Q1: A copy-on-write ring buffer
Wrap Lesson 30’s circular buffer, stored in a private class, in a structure
RingDeque<Element> with value semantics: addFirst, addLast,
removeFirst, removeLast, count, and toArray. Count copies, and test
that a copy is made only when a shared deque is changed.
Show solution
var copies = 0
struct RingDeque<Element> {
private final class Buffer {
var items: [Element?]
var first = 0
var count = 0
init(capacity: Int) {
items = [Element?](repeating: nil, count: capacity)
}
func copy(capacity: Int? = nil) -> Buffer {
let copy = Buffer(capacity: capacity ?? items.count)
for i in 0..<count {
copy.items[i] = items[(first + i) % items.count]
}
copy.count = count
return copy
}
}
private var buffer = Buffer(capacity: 4)
private mutating func prepareToWrite() {
if !isKnownUniquelyReferenced(&buffer) {
buffer = buffer.copy()
copies += 1
}
if buffer.count == buffer.items.count {
buffer = buffer.copy(capacity: buffer.items.count * 2)
}
}
var count: Int { buffer.count }
mutating func addFirst(_ item: Element) {
prepareToWrite()
buffer.first = (buffer.first - 1 + buffer.items.count) % buffer.items.count
buffer.items[buffer.first] = item
buffer.count += 1
}
mutating func addLast(_ item: Element) {
prepareToWrite()
buffer.items[(buffer.first + buffer.count) % buffer.items.count] = item
buffer.count += 1
}
mutating func removeFirst() -> Element? {
guard count > 0 else { return nil }
prepareToWrite()
let item = buffer.items[buffer.first]
buffer.items[buffer.first] = nil
buffer.first = (buffer.first + 1) % buffer.items.count
buffer.count -= 1
return item
}
mutating func removeLast() -> Element? {
guard count > 0 else { return nil }
prepareToWrite()
let last = (buffer.first + buffer.count - 1) % buffer.items.count
let item = buffer.items[last]
buffer.items[last] = nil
buffer.count -= 1
return item
}
var toArray: [Element] {
(0..<buffer.count).map { buffer.items[(buffer.first + $0) % buffer.items.count]! }
}
}
var a = RingDeque<Int>()
for n in 1...10 {
a.addLast(n)
}
assert(copies == 0)
var b = a
_ = b.removeFirst()
b.addFirst(0)
assert(copies == 1)
assert(a.toArray == Array(1...10) && b.toArray == [0] + Array(2...10))
_ = a.removeLast()
assert(copies == 1) // a is unique again once b has its own bufferGrowing also replaces the buffer, so prepareToWrite handles both reasons to
get a new one. The guard in the remove methods comes before
prepareToWrite, so removing from an empty shared deque does not copy it for
nothing.
Q2: Snapshots for undo
Write a Document structure holding an array of lines, and an Editor that
keeps a history of Document values so that undo() restores the previous
one. Explain why keeping a whole document per step is affordable.
Show solution
struct Document: Equatable {
var lines: [String] = []
}
struct Editor {
private(set) var document = Document()
private var history: [Document] = []
mutating func perform(_ change: (inout Document) -> Void) {
history.append(document)
change(&document)
}
mutating func undo() {
if let previous = history.popLast() {
document = previous
}
}
}
var editor = Editor()
editor.perform { $0.lines.append("Dear Ada,") }
editor.perform { $0.lines.append("Thanks for the program.") }
editor.perform { $0.lines[1] = "Thanks for the notes." }
assert(editor.document.lines == ["Dear Ada,", "Thanks for the notes."])
editor.undo()
assert(editor.document.lines == ["Dear Ada,", "Thanks for the program."])
editor.undo()
editor.undo()
editor.undo() // nothing left to undo: no effect
assert(editor.document == Document())Appending document to history copies only a reference to the lines
array’s buffer. The next change then copies the buffer once, so each step
costs one copy of the document, made when the step happens, and old
snapshots never change afterwards. With a class instead, every snapshot would
be the same object, and undo would restore nothing.
Q3: Finding the accidental copy
This loop is meant to build a stack of 10,000 items with no copies, but it
makes 10,000 copies. Find the reason, and fix it without changing Stack.
var stack = Stack()
var last = stack
for n in 0..<10_000 {
stack.push(n)
last = stack
}
Show solution
var copies = 0
struct Stack {
private final class Storage {
var items: [Int] = []
}
private var storage = Storage()
mutating func push(_ item: Int) {
if !isKnownUniquelyReferenced(&storage) {
let fresh = Storage()
fresh.items = storage.items
storage = fresh
copies += 1
}
storage.items.append(item)
}
var top: Int? { storage.items.last }
}
var stack = Stack()
for _ in 0..<10_000 {
stack.push(1)
}
let last = stack
assert(copies == 0 && last.top == 1)last = stack at the end of each iteration makes the storage shared, so the
next push finds two owners and copies. Taking the snapshot once, after the
loop, keeps the storage unique throughout. The same thing happens in real
code with a property that caches “the previous value”, and it turns a
linear-time loop into a quadratic one without changing a single visible
result.
Q4: A generic copy-on-write box
Write a generic CowBox<Value> that holds any value in a class, with a
value property whose getter reads the shared storage and whose setter
copies the storage first when it is shared. Show that it gives a class,
here a Canvas of pixels, value semantics, as long as
every change goes through the box.
Show solution
final class Canvas {
var pixels: [Int]
init(pixels: [Int]) { self.pixels = pixels }
func clone() -> Canvas { Canvas(pixels: pixels) }
}
struct CowBox<Value> {
private final class Reference {
var value: Value
init(_ value: Value) { self.value = value }
}
private var reference: Reference
private let clone: (Value) -> Value
init(_ value: Value, clone: @escaping (Value) -> Value) {
reference = Reference(value)
self.clone = clone
}
var value: Value {
get { reference.value }
set {
if !isKnownUniquelyReferenced(&reference) {
reference = Reference(newValue)
} else {
reference.value = newValue
}
}
}
/// Change the value in place, copying it first if it is shared.
mutating func modify(_ change: (Value) -> Void) {
if !isKnownUniquelyReferenced(&reference) {
reference = Reference(clone(reference.value))
}
change(reference.value)
}
}
var first = CowBox(Canvas(pixels: [0, 0, 0])) { $0.clone() }
var second = first
second.modify { $0.pixels[1] = 9 }
assert(first.value.pixels == [0, 0, 0] && second.value.pixels == [0, 9, 0])
first.modify { $0.pixels[0] = 1 }
assert(first.value.pixels == [1, 0, 0])A class value can be changed without assigning to anything, through
first.value.pixels[0] = 1, and that would bypass the box entirely. So the box
offers modify, which clones the object first when it is shared, and the
value semantics hold only for changes made that way. This is why copy-on-write
is normally built into a type’s own mutating methods, as in the lesson, rather
than bolted on from outside.
Q5 (optional): Sharing without copying
Copy-on-write shares until a change, then copies everything. An immutable
linked list, like Lesson 12’s enum, never copies: adding to the front makes a
new node pointing at the old list, and both lists share all the old nodes.
Write PersistentStack<Element> this way, with pushing(_:) and popping()
returning new stacks, and show that a thousand versions of a stack share their
nodes.
Show solution
var nodesCreated = 0
struct PersistentStack<Element> {
private final class Node {
let item: Element
let next: Node?
init(_ item: Element, _ next: Node?) {
self.item = item
self.next = next
nodesCreated += 1
}
}
private let head: Node?
let count: Int
init() {
head = nil
count = 0
}
private init(head: Node?, count: Int) {
self.head = head
self.count = count
}
var top: Element? { head?.item }
func pushing(_ item: Element) -> PersistentStack {
PersistentStack(head: Node(item, head), count: count + 1)
}
func popping() -> PersistentStack {
PersistentStack(head: head?.next, count: max(count - 1, 0))
}
}
var versions = [PersistentStack<Int>()]
for n in 1...1_000 {
versions.append(versions.last!.pushing(n))
}
assert(nodesCreated == 1_000) // one node per version, not 500,500
assert(versions[10].top == 10 && versions[1_000].count == 1_000)
assert(versions[1_000].popping().top == 999)Each version is one node plus everything before it, shared. The nodes can be
shared safely because they never change: let all the way down. This is the
persistent data structure approach of functional languages, from Lesson
19. It fits stacks and trees well; copy-on-write fits arrays, where changing
one element in place is the whole point.
What’s next
That completes the data structures of Unit 4. Unit 5 asks how fast they are, precisely: asymptotic analysis, starting next lesson.