Sub topic 9
Costs and trade-offs against mutable and fully copied data
This chapter assumes you know Big-O notation, the difference between a reference and a copy, and the path-copying idea from earlier chapters. It compares three ways to "update" a collection: mutate it in place, copy it fully, or update it persistently with structural sharing.
The three strategies
- Mutable update. Change the structure in place. The old version is gone.
- Full copy. Copy every element into a new structure, then change the copy. The old version stays valid.
- Persistent update. Copy only the nodes on the path to the change and share the rest. The old version stays valid.
Persistent updates sit between the other two. They keep the safety of a full copy and come close to the speed of a mutation.
Time costs
Costs for a collection of n elements:
| Operation | Mutable array | Full copy of array | Persistent vector (32-way trie) | Persistent balanced tree |
|---|---|---|---|---|
| Read by index | O(1) | O(1) | O(log32 n) | O(log n) |
| Update one element | O(1) | O(n) | O(log32 n) | O(log n) |
| Keep the old version | not possible | O(n) per version | O(log32 n) per version | O(log n) per version |
For a vector, log32 n is at most 7 for a billion elements, so people often call it "effectively constant". It is not O(1). Each read follows several pointers, and each step can miss the CPU cache. A flat array is contiguous in memory, so it is usually much faster for reads and scans.
Space costs
Each update allocates new nodes along one path. In the binary tree from earlier chapters, an insert allocates about log n nodes, not n. Two versions that differ by one key share almost everything.
The total memory for k versions is roughly the size of the first version plus k times the path length. A full copy costs k times n.
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Tree:
key: int
left: Optional["Tree"] = None
right: Optional["Tree"] = None
def insert(t: Optional[Tree], key: int) -> Tree:
if t is None:
return Tree(key)
if key < t.key:
return Tree(t.key, insert(t.left, key), t.right)
if key > t.key:
return Tree(t.key, t.left, insert(t.right, key))
return t
def count_new_nodes(old: Optional[Tree], new: Optional[Tree]) -> int:
"""Count nodes in `new` that are not the same object as in `old`."""
if new is None or new is old:
return 0
if old is None:
return 1 + count_new_nodes(None, new.left) + count_new_nodes(None, new.right)
return (1
+ count_new_nodes(old.left, new.left)
+ count_new_nodes(old.right, new.right))
root = None
for k in [50, 25, 75, 12, 37, 62, 87, 6, 18, 31, 43]:
root = insert(root, k)
updated = insert(root, 40)
print(count_new_nodes(root, updated)) # 5The tree holds 11 nodes. Inserting 40 allocates 5 new nodes: the four on the path (50, 25, 37, 43) and the new leaf 40. The other 7 nodes are shared.
Where the extra cost comes from
- Constant factors. Each node is a separate object with a header and pointers. An array stores raw values side by side.
- Cache behavior. Following pointers across the heap is slower than scanning a contiguous block.
- Allocation pressure. Every update creates short-lived objects. The garbage collector must reclaim the replaced path nodes.
- Write amplification. Changing one leaf copies up to a whole path, and each copied trie node holds up to 32 slots.
What you get in return
- Cheap snapshots. Keeping an old version costs a reference, not a copy.
- Safe sharing. Any code that holds a version can rely on it never changing, so no locks are needed to read it.
- Fast change detection. If
new is old, nothing changed. If a subtree is the same object, it can be skipped.
Choosing a strategy
Rules of thumb:
- If nobody else needs the old value, mutate in place. It is the fastest option.
- If the collection holds a few dozen items, copy it. The code is simpler and the copy is cheap.
- If you keep many versions of a large collection, or share it across threads or components, use a persistent structure.
- If you build a large structure once and then freeze it, batch the updates. The next chapter covers transients for this.
Exercise
A list of 1,000,000 items is updated 1,000 times, and every intermediate version must stay available. Compare the approximate memory growth of full copies and a persistent 32-way vector, and name one cost the persistent vector adds.
Show answer
Full copies store about 1,000 × 1,000,000 = 1 billion element slots. The persistent vector shares most nodes and allocates only one path per update, about 4 nodes of up to 32 slots each, so roughly 1,000 × 4 × 32 = 128,000 slots, plus the original million. The persistent vector adds slower reads and scans than a flat array, because of pointer chasing and worse cache locality, and it adds allocation work for the garbage collector.