Sub topic 3
Structural sharing: reusing unchanged parts
This chapter assumes you can read basic Python and JavaScript, know linked lists and binary search trees, understand Big-O notation, and know the difference between an object reference and a copy.
The idea
Structural sharing means that two versions of a value reuse the nodes they have in common. When you "change" an immutable structure, you don't copy all of it. You build only the new nodes that differ, and you point them at the old nodes that stayed the same.
This works because the old nodes are immutable. Nobody can modify a shared node, so nobody can be surprised by a change made through the other version.
Sharing in a linked list
Prepending to an immutable list allocates one node. The existing list becomes the tail of the new one.
from typing import NamedTuple, Optional
class Node(NamedTuple):
head: int
tail: Optional["Node"]
xs = Node(2, Node(3, None))
ys = Node(1, xs) # new version: prepend 1
zs = Node(0, xs) # another version: prepend 0
assert ys.tail is xs
assert zs.tail is xs
assert ys.tail is zs.tail # both versions share the same tail nodesThe is operator compares identity, not equality. ys.tail is zs.tail is true because both fields hold a reference to the same object in memory. Three versions exist (xs, ys, zs), but only five nodes were allocated in total, not the eight that three full copies would need.
Sharing along a path
Sharing is not limited to a tail. In a tree, an update changes one path from the root to a node. Every subtree off that path stays the same, so the new version can point to it directly.
JavaScript's spread syntax lets you do this by hand:
const a = { user: { name: "Ada" }, items: [1, 2, 3] };
const b = { ...a, user: { ...a.user, name: "Grace" } };
console.log(b.items === a.items); // true: unchanged branch is shared
console.log(b.user === a.user); // false: changed branch is copied
console.log(a.user.name); // "Ada": the old version is intactThe spread { ...a } copies only the top-level fields, and those fields are references. That is a shallow copy, and here it is exactly what you want. You copy each object on the route to the change, and you leave everything else alone.
What you gain
Each update costs time and memory proportional to the part that changed, plus the route to it. It does not cost the size of the whole structure.
| Operation | Full copy | Structural sharing |
|---|---|---|
| Prepend to list of n items | O(n) | O(1) |
| Update one key in a balanced tree of n keys | O(n) | O(log n) |
| Keep k old versions | O(k · n) memory | O(n + total changes) memory |
A second benefit is cheap change detection. If b.items === a.items, you know nothing under items changed, and you skip comparing it element by element. UI libraries use this reference check to decide what to redraw.
Common errors
- Mutating a shared node. If you call
a.items.push(4), the change appears inbas well, because both versions hold the same array. Sharing is only safe when shared parts are never changed. Freeze objects (Object.freezein JavaScript,frozen=Trueon a Python dataclass) or use a library that enforces immutability. - Assuming
==means shared. Two structures can be equal without sharing memory. Equal values built separately are separate copies, and a reference check on them returns false. - Deep-copying "to be safe."
copy.deepcopyorJSON.parse(JSON.stringify(x))throws away all sharing. It makes every update O(n) and breaks reference-based change detection, because every node becomes a new object. - Shallow-copying only the top level.
{ ...a, user: { name: "Grace" } }is fine. But{ ...a }followed byb.user.name = "Grace"still mutates the object thatashares.
Exercise
Given a = { user: { name: "Ada" }, items: [1, 2, 3] }, you run const b = { ...a, items: [...a.items, 4] }. Which of b.user === a.user and b.items === a.items is true, and why?
Show answer
b.user === a.user is true, because user was not touched and the spread copied only the reference. b.items === a.items is false, because [...a.items, 4] builds a new array. The old array still holds [1, 2, 3].