Sub topic 12
Where persistent structures pay off, and pitfalls
This chapter assumes you know path copying, structural sharing, and the cost of persistent lists, trees, vectors, and hash maps. It covers where those structures help in practice and where they cause trouble. The target length is about 650 words.
Where they pay off
Persistent structures fit best when you need to keep old versions or compare them cheaply. Four uses come up most often.
- Undo and redo. Keep a stack of versions. Each edit adds one new version that shares most of its memory with the last one, so history costs a small amount per step instead of a full copy.
- Snapshots. A reader can hold a reference to one version while a writer builds the next. Nothing the reader sees can change, so it needs no lock.
- Concurrency. Immutable nodes can be read from many threads without synchronization. Only the single reference to the "current" version needs to be updated safely.
- Change detection. If a branch of the data is unchanged, the new version holds the same object as the old one. A reference comparison can then skip the whole branch.
Change detection by reference
The JavaScript example below shows the idea. It updates only the path to the change and compares branches with ===.
const a = { user: { name: "Ada" }, items: [1, 2, 3] };
const b = { ...a, user: { ...a.user, name: "Grace" } };
function changedKeys(prev, next) {
return Object.keys(next).filter((k) => prev[k] !== next[k]);
}
console.log(changedKeys(a, b)); // ["user"]
console.log(b.items === a.items); // true: shared, so no deep check neededThe check costs one comparison per key, no matter how large items is. This is why UI libraries that expect immutable state can decide what to re-render quickly.
Pitfalls
Mutating a shared node
Sharing is only safe if nobody changes a shared node. One in-place write corrupts every version that points to it. In languages without enforced immutability, this is the most common bug.
from dataclasses import dataclass
@dataclass
class Box:
items: list
v1 = Box([1, 2, 3])
v2 = Box(v1.items) # shares the same list
v2.items.append(4) # mutates shared state
print(v1.items) # [1, 2, 3, 4]: the old version changedUse frozen dataclasses, tuples, or a library that enforces immutability, and avoid mutable fields inside shared nodes.
Shallow copies that break sharing
Spread syntax and dict(...) copy only one level. If you forget to copy the nested object on the path to the change, you either mutate a shared child or lose the sharing guarantee. Copy every level on the path, and no others.
Copying everything "to be safe"
A deep copy on every update gives correct results but removes the benefit. Reference comparison then reports every branch as changed, and cost grows with the size of the whole structure.
Memory retention
Old versions stay alive while anything references them. A long undo stack, or a cache of snapshots, keeps shared nodes in memory, and it can also keep large replaced nodes alive. Cap history length and drop references you no longer need.
Constant factors
Persistent vectors and maps are effectively O(log32 n) for reads and updates, but each operation touches several nodes and allocates new ones. For a tight loop that builds one large structure and discards every intermediate version, a mutable structure or a transient (a temporary mutable form of a persistent structure) is faster.
Choosing
| Situation | Better choice |
|---|---|
| Need undo, snapshots, or cheap diffing | Persistent |
| Many readers, rare writes | Persistent |
| One writer, no old versions needed | Mutable |
| Bulk build, then freeze | Transient or batch update |
Exercise
A state object holds a 100,000-element array and a small settings object. You change one setting using a deep copy of the whole state, then check next.items === prev.items. What does the check return, and what should you change?
Show answer
It returns false, because the deep copy created a new array. Copy only the path to the change (the root and the settings object) and reuse the existing items reference, so the check returns true and the unchanged branch is skipped.