Sub topic 1
Why Immutable Values Need Cheap Updates
An immutable value never changes after it is created. This chapter explains why that property is useful and why naive updates to such values are expensive. It also introduces the idea that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you can do the following:
- Read Python and basic JavaScript.
- Explain the difference between an object reference and a copy.
- Read Big-O notation such as O(1), O(log n), and O(n).
- Describe a linked list and a binary search tree at a basic level.
What immutability gives you
With an immutable value, "changing" it means building a new value and leaving the old one alone. This gives you three things.
- Safe sharing. Any code that holds a reference can rely on the value staying the same. No other part of the program can alter it behind your back.
- Cheap snapshots. Keeping an old version is just keeping a reference to it. Undo history and time-travel debugging work this way.
- Simple concurrency. Threads can read the same value without locks, because nobody writes to it.
Immutability also makes change detection simple. If the old and new references are the same object, nothing changed.
The cost of the naive approach
The simplest way to "update" an immutable collection is to copy all of it and change the copy. Here is that approach in Python:
def with_item(items: tuple, index: int, value) -> tuple:
copy = list(items) # O(n): copies every element
copy[index] = value
return tuple(copy)
v1 = tuple(range(5))
v2 = with_item(v1, 2, 99)
print(v1) # (0, 1, 2, 3, 4)
print(v2) # (0, 1, 99, 3, 4)The old version v1 stays valid, which is what we want. But the update costs O(n) in time and memory, even though only one element changed. Building a collection of n items by repeated updates costs O(n²) in total.
The same problem appears in JavaScript when you spread a large array or object on every change:
let state = { count: 0, log: [] };
for (let i = 0; i < 5; i++) {
state = { ...state, count: state.count + 1, log: [...state.log, i] };
}
console.log(state.count); // 5
console.log(state.log.length); // 5Each pass copies the whole log array. The shallow spread of state is cheap because it has two fields. The array spread grows with the data.
The key observation
Most of the old version is identical to the new version. If you update one element in a large collection, the other elements are the same in both. Copying them is wasted work.
Because the values are immutable, the two versions can safely point at the same memory for the parts that did not change. Nobody can modify that shared memory, so sharing cannot cause bugs. This technique is called structural sharing. A data structure that keeps old versions usable after an update is called persistent.
The goal of a persistent data structure is to make an update cost roughly the size of the change, or a small factor above it, instead of the size of the whole collection. Later chapters show how: a list shares its tail, a tree copies only the path to the change, and wide tries keep that path very short.
What to expect from the rest of the tutorial
| Structure | Typical update cost | Chapter idea |
|---|---|---|
| Full copy of an array | O(n) | The baseline to beat |
| Persistent list (prepend) | O(1) | Share the tail |
| Persistent balanced tree | O(log n) | Path copying |
| Persistent vector, hash map | O(log32 n) | Wide tries |
Common mistakes at this stage
- Assuming immutable means slow. Naive copying is slow. Structures designed for sharing are not.
- Assuming a shallow copy is enough. In JavaScript,
{ ...a }copies only the top level. Nested objects are still shared, and mutating them changes both versions. Immutability only holds if you never mutate anything you share. - Confusing a read-only reference with an immutable value. A
constbinding or a read-only view does not stop other code from mutating the underlying object.
Exercise
A program stores 100,000 items in an immutable array and appends one item per event using a full copy. Roughly how many element copies happen after 1,000 events, and what idea avoids most of that work?
Show answer
Each append copies about 100,000 or more elements, so 1,000 events copy on the order of 100 million elements in total. Structural sharing avoids this: the new version reuses the unchanged elements of the old version and allocates only the nodes that differ, which is safe because shared values are never modified.
Exercise
In the JavaScript example, b = { ...a, user: { ...a.user, name: "Grace" } } is used in place of { ...a } followed by b.user.name = "Grace". Why is the second form wrong for immutable values?
Show answer
A plain { ...a } is a shallow copy, so b.user is the same object as a.user. Setting b.user.name also changes a.user.name, which destroys the old version.