Search

Search papers and lessons

Immutability

Level 2 · 10 min read

An immutable value never changes after it is created, so every change produces a new value and the old one stays intact.

On this page

  • Colour = topic mix
  • Discrete math
  • Algorithms
  • Programming languages
  • Calculus
  • Sign in to see your progress

TL;DR

An immutable value cannot be changed after it is created. To "change" it, you build a new value that differs from the old one, and the old value stays exactly as it was. Because nothing mutates in place, code that holds a reference to a value can trust that the value will not shift under it.

The obvious objection is cost: copying everything on every change would be slow. Persistent data structures avoid most of that cost by sharing the unchanged parts between the old and new values. This style is central to Functional Programming.

Where you'll see it: in the state management of user interfaces, where each screen is a snapshot, in functional languages such as Haskell and Clojure, and in version control systems that store each commit as an unchangeable snapshot.

Intuition

A photograph, not a whiteboard

Think of the difference between a whiteboard and a stack of photographs. If you erase a number on the whiteboard, the old number is gone, and anyone who copied it down earlier now has a wrong copy. If instead you take a new photograph after each edit, every photograph stays correct forever. You can compare the old and new photos, go back to any of them, and share them with people without worrying that they will change.

An immutable value is a photograph. A mutable value is the whiteboard.

Why the idea exists

Mutation makes programs hard to reason about. Suppose a function receives a list and returns a result. If the function also quietly changes the list, the caller may get a surprise later. When several parts of a program share one mutable object, a change made in one place can break another place that never knew about it. With several threads (independent streams of execution in one program) running at once, the problem becomes a race, covered in race conditions.

Immutability removes this whole class of bug. If a value can never change, sharing it is always safe. Any number of readers can hold it at once, and nothing needs a lock to protect it.

A small picture

Here is the basic flow. An update never touches the old value.

flowchart LR
  A["v1 = [1, 2, 3]"] -->|"put 0 in front"| B["v2 = [0, 1, 2, 3]"]
  B -.->|"new cell 0 points at the first cell of v1"| A

The new list v2v_2 does not copy v1v_1. It is one new cell holding 00 that points at the existing cells of v1v_1. Both lists are valid, and neither can be damaged by the other.

The math

Immutability is a property of how values are used, not a formula, but it can be stated precisely. A value vv is immutable if no operation changes vv after it has been created. An operation ff that "updates" vv must return a new value v′=f(v)v' = f(v), and vv itself must still satisfy the same description it had before.

Sharing

Let nn be the number of nodes in a structure and kk the number of nodes that differ between vv and v′v'. A naive copy costs nn new nodes for each update. A persistent structure aims to cost roughly kk new nodes, reusing the other n−kn - k nodes by reference (a reference is a pointer to an existing object rather than a copy of it). The ratio k/nk/n of new work to total size is the key number to watch.

Path copying

Most persistent trees use path copying. (A persistent Array is usually stored as such a tree too, which is why it can avoid copying everything on each update.) To update one node, copy only the nodes on the path from the root down to that node. Every other node is shared, because it is not on the path.

If a balanced binary tree has depth dd, meaning d+1d+1 nodes lie on any root-to-leaf path, then one leaf update creates d+1d+1 new nodes. The total number of nodes is 2d+1−12^{d+1} - 1 for a complete tree, so the update creates a tiny fraction of the structure.

Worked examples

Example
1. A list with three items

Start with the value v1=[1,2,3]v_1 = [1, 2, 3].

  1. Mutable approach. Insert 00 at the front of the list in place. The list [1,2,3][1, 2, 3] now reads [0,1,2,3][0, 1, 2, 3], and any other variable that pointed to it also reads [0,1,2,3][0, 1, 2, 3].
  2. Immutable approach. Compute v2=0::v1v_2 = 0 :: v_1, where :::: means "put this item in front, returning a new list". Now v2=[0,1,2,3]v_2 = [0, 1, 2, 3] and v1=[1,2,3]v_1 = [1, 2, 3] still.
  3. Count. A naive copy of v1v_1 with 00 added builds 4 new cells. A persistent linked list builds only 1 new cell (holding 00) that points at the three existing cells, so 3 of the 4 cells in v2v_2 are shared.
  4. Caveat. Sharing works because the new item goes at the front. Adding at the back of a linked list would force a copy of every cell, since each cell points to the next one. That is why persistent structures are designed around which updates they make cheap.
  5. Interpretation. The old value is still usable, so you can keep it for undo or for comparison, and it costs almost nothing extra to keep.
Example
2. Path copying in a binary tree

Take a complete binary tree of depth d=2d = 2. It has 23−1=72^3 - 1 = 7 nodes: a root TT, two children LL and RR, and four leaves LLLL, LRLR, RLRL, RRRR. Now replace the value at leaf LRLR.

  1. The path from the root to LRLR is T→L→LRT \to L \to LR. These three nodes must change.
  2. Create new copies T′T', L′L' and LR′LR'. Point T′T' at L′L' and at the old RR. Point L′L' at LR′LR' and at the old LLLL.
  3. Shared nodes. The old RR, LLLL, RLRL and RRRR are unchanged, so the new tree points to the same objects. That is four shared nodes.
  4. Count. The update creates 33 new nodes and reuses 44.
  5. Interpretation. Both the old and new trees are complete, valid trees. The old one still returns the old value at LRLR.

Scale this up. A balanced tree with 2202^{20} leaves has depth 2020, so an update copies 2121 nodes. The tree has 221−1=2,097,1512^{21} - 1 = 2{,}097{,}151 nodes, so the update creates about 21/2,097,151≈0.001%21 / 2{,}097{,}151 \approx 0.001\% of the structure. The rest is shared.

Example
3. Realistic: a shared counter that is safe to read

A program has a shared counter that starts at 55. Two threads each want to add 11.

With mutation and no lock:

  1. Thread A reads the counter and gets 55.
  2. Thread B reads the counter and gets 55.
  3. Thread A writes 5+1=65 + 1 = 6.
  4. Thread B writes 5+1=65 + 1 = 6, overwriting A's write.
  5. Result. The counter is 66, but two increments happened, so the correct answer is 77. One update is lost.

With immutable values and an atomic swap (an operation that the hardware performs as one indivisible step), each thread computes a new value from the value it read and swaps it in only if the counter still holds the value it read. This pattern is called compare-and-swap. If the swap fails, that thread reads again and retries. The lost update cannot happen, because the swap fails for the thread that read a stale value, and that thread recomputes from the new one. Nothing is ever overwritten blindly, and an old value is never changed under a reader. The cost is retries when threads collide, which is usually cheaper than a lock held over a long computation.

This is the reason many concurrent systems favour immutable snapshots. Readers take a snapshot and work on it without coordination.

Tradeoffs and failure modes

Immutability makes code simpler to reason about, but it has real costs. It helps most when many parts of a program read the same data, and it hurts when a program does many small in-place updates to very large arrays.

SituationProblemBetter choice
Shared data read by many parts or threadsMutation causes surprises and racesImmutable values, with snapshots for readers
Large array updated one element at a timeCopying the whole array on each update is slowMutable array inside a local scope, or a persistent vector with path copying
Memory-constrained programOld versions stay alive while referencedRelease old snapshots, or rely on Garbage Collection, which reclaims values nothing refers to any more
Frequent updates to a single small recordAllocating new objects adds overheadPlain mutation may be simpler and fast enough
Hidden mutation inside a "constant" objectThe guarantee is falseMake the whole object graph immutable, or document clearly what is shared

A common mistake is to call an object immutable while it holds a mutable list inside. The outer value cannot change, but the inner list can, so the guarantee is broken. Deep immutability needs every part of the structure to be immutable.

History

Lisp, designed by John McCarthy around 1958, built programs around lists made of linked cells, and its style of building new lists out of old ones, sharing the unchanged tails, anticipated persistent data structures. (Lisp itself still allowed in-place edits.) In the 1980s, Driscoll, Sarnak, Sleator and Tarjan studied how to make linked data structures persistent in general. Chris Okasaki's 1998 book Purely Functional Data Structures showed how to design efficient immutable structures, and it made persistent data structures a practical topic rather than a curiosity. Later languages such as Clojure, released in the late 2000s, built large parts of their standard collections on persistent structures. The idea caught on because multi-core hardware made shared mutable state harder to manage, and immutable values offered a simpler way to share data safely.

Recap

An immutable value never changes, so every update returns a new value and the old one remains valid. Persistent structures make this affordable by sharing unchanged parts through path copying, so an update to a large tree creates only a few new nodes (and a front insertion into a linked list creates one). Immutability removes a large class of bugs caused by shared mutable state, especially in concurrent code covered by race conditions. The style is central to functional programming. The tree that makes path copying concrete is the binary tree, and a linked list is the simplest persistent structure.

Check yourself

QuestionRecall: what is the difference between an immutable value and a mutable one?Show answer

An immutable value cannot be changed after it is created. An update must produce a new value, and the old one stays the same. A mutable value can be changed in place, so the same object can read differently at different times and through different references.

QuestionComputation: a complete binary tree has depth 3, so a root-to-leaf path has 4 nodes. How many new nodes does one leaf update create, and how many nodes does the tree have in total?Show answer

One leaf update creates one new copy for each node on the path, so 4 new nodes. A complete binary tree with depth 3 has 24−1=152^4 - 1 = 15 nodes in total. The update therefore reuses 15−4=1115 - 4 = 11 nodes.

QuestionWhy: why does an immutable update keep the old value useful, and what does that buy a program?Show answer

The old value is never edited, so it still describes the state before the update. Programs can keep it for undo, compare it with the new value, or hand it to another thread without copying, because no one can change it. That is why readers need no locks.

QuestionApplied: a team stores a configuration object as immutable, but one of its fields is a mutable list that other code appends to at runtime. The team says the config is immutable. What is wrong, and how would you fix it?Show answer

The outer object cannot change, but the list inside it can, so the configuration can still change in ways that surprise readers. Deep immutability needs the list to be immutable too. The fix is to store an immutable list, so each addition returns a new list and the config object is rebuilt with the new list, or to make the field read-only and copy it on read.

Sources