Sub topic 14
Choosing an Approach: Performance and Design Trade-offs
This chapter assumes you have worked through the earlier chapters. You should be comfortable with spread copies, the non-mutating array methods, nested updates, Object.freeze, structuredClone, structural sharing, reference equality, and Immer's produce. Here we compare these tools by what they cost and what they give you, so you can choose one deliberately.
Immutability does not have to be all or nothing. Most codebases mix approaches. They use plain spread for small state, Immer for deep or awkward updates, and local mutation inside functions that build fresh data. The goal is to know where each approach costs time, memory, or clarity.
The Cost Model of Copying
Every immutable update allocates something. To reason about cost, count what gets copied.
- A spread of an object or array copies every top-level entry. That costs O(n) in the size of that level.
- A nested update copies one object per level along the changed path. Sibling branches are shared, so the cost is the sum of the sizes of the objects on the path, not the size of the whole tree.
structuredClonecopies everything, every time. Its cost grows with the whole tree, and it throws away all sharing.- Persistent data structures such as Immutable.js copy a small, fixed-size node per level of an internal tree. An update costs O(log n) with a large base, so it stays cheap even for huge collections.
For typical application state with dozens or hundreds of keys, a spread copy is cheap enough not to matter. The problems appear in two places: very large collections, and copies made inside loops.
The Quadratic Trap
The most common performance bug in immutable code is spreading an accumulator on every iteration. Each step copies everything built so far, so the total work grows with the square of the input size.
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i, value: i * 2 }));
console.time('spread in reduce');
const slow = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});
console.timeEnd('spread in reduce');
console.time('Object.fromEntries');
const fast = Object.fromEntries(items.map(item => [item.id, item]));
console.timeEnd('Object.fromEntries');
console.time('local mutation');
const local = {};
for (const item of items) {
local[item.id] = item;
}
console.timeEnd('local mutation');
console.log(Object.keys(slow).length, Object.keys(fast).length, Object.keys(local).length);
// 5000 5000 5000Run this in Node. The reduce version is usually hundreds of times slower than the other two, and the gap widens as the input grows. All three produce an equivalent new object. None of them changes items.
Enforcement Versus Convention
Immutability can be a convention your team follows, or a rule the runtime enforces. Each choice has a cost.
| Approach | What it enforces | Runtime cost | Main risk |
|---|---|---|---|
| Convention only (spread, `map`, `filter`) | Nothing | Lowest | One accidental mutation breaks change detection silently |
| `Object.freeze` / deep freeze | Writes throw in strict mode | Walks the whole object on every freeze | Shallow by default; cost on large trees |
| TypeScript `readonly` / `Readonly<T>` | Compile-time errors | None at runtime | Can be cast away; does not reach untyped code |
| Immer `produce` | Auto-freezes results by default | Proxy overhead per update | Hidden cost in hot loops |
| Immutable.js | API exposes no mutating methods | Conversion to and from plain objects | Lock-in and interop friction |
A common compromise is to freeze only during development. Bugs surface as errors while you test, and production does not pay for the freezing.
'use strict';
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
return Object.freeze(obj);
}
const isDev = process.env.NODE_ENV !== 'production';
function freezeInDev(obj) {
return isDev ? deepFreeze(obj) : obj;
}
const state = freezeInDev({ user: { name: 'Ada' } });
try {
state.user.name = 'Grace';
} catch (err) {
console.log(err instanceof TypeError); // true when NODE_ENV is not 'production'
}The !Object.isFrozen(value) check skips subtrees that are already frozen. Without it, freezing new state that shares most of its branches with old frozen state would walk the shared branches again. With it, the cost of freezing after an update stays close to the cost of the update.
Reference Equality Only Works With Discipline
Change detection by reference (prev !== next) is the main payoff of immutable state. It makes memoization, React re-render checks, and selector caching cheap. It can fail in two opposite ways.
- False negatives. Someone mutates an object in place. The reference stays the same, so the change goes unnoticed and the UI shows stale data. No error is raised.
- False positives. An update creates new references when nothing changed.
filterandmapalways return a new array, even when they keep every element. Each needless new reference triggers recomputation downstream.
Guard against false positives by returning the original value when an update would be a no-op:
function setTheme(state, theme) {
if (state.settings.theme === theme) return state;
return { ...state, settings: { ...state.settings, theme } };
}
function removeTodo(todos, id) {
const next = todos.filter(t => t.id !== id);
return next.length === todos.length ? todos : next;
}
const state = { settings: { theme: 'dark' }, todos: [{ id: 1 }] };
console.log(setTheme(state, 'dark') === state); // true, no change
console.log(removeTodo(state.todos, 42) === state.todos); // true, nothing removed
console.log(removeTodo(state.todos, 1) === state.todos); // false, an item was removedImmer does this for you. If a recipe changes nothing, produce returns the original object. If it assigns a value equal to the current one, Immer also treats that as no change.
Immer: Convenience at a Measured Price
Immer removes most of the boilerplate of nested spreads and makes accidental mutation of the original impossible inside a recipe. Its costs are specific:
- Proxy overhead. Each property you read or write in a draft goes through a Proxy. For a single update on application state this is negligible. For tens of thousands of updates in a tight loop, or for one recipe that touches every element of a large array, plain code can be several times faster.
- Auto-freeze. Immer freezes the objects it produces by default. Freezing walks new nodes, which adds cost on large results. You can turn it off with
setAutoFreeze(false)if profiling shows it matters. - Restrictions on what drafts can hold. Class instances are not drafted unless they are marked with the
immerablesymbol. Mixing "return a new value" with "mutate the draft" in the same recipe throws an error. - Bundle size. Immer is a small dependency, but it is still one more thing to ship and keep up to date.
A good rule is to use Immer where nested updates would otherwise be three or more spreads deep, and to keep plain code for bulk transformations.
Persistent Data Structures: When They Earn Their Keep
Immutable.js and similar libraries store data in tries, which are trees with a wide fan-out. An update copies only a short path of small nodes. Very large collections benefit. Changing one element in a list of a million items is fast, while with or a spread would copy the whole array.
The costs are about design rather than speed:
- Values are not plain objects. You write
map.get('user')instead ofobj.user, and normal destructuring,JSON.stringifybehaviour, and many libraries do not work without conversion. - Converting with
toJS()copies the whole structure and returns new references every time it is called. Calling it in a render path defeats reference-equality checks completely. - The library shapes your types, tests, and API boundaries, so removing it later is expensive.
Most applications never reach the size where this pays off. Reach for persistent structures when profiling shows that copying large collections is a real bottleneck, not as a default.
A Decision Guide
Use structuredClone for snapshots, undo history that must not share anything with live data, or copies passed to code you do not trust. Do not use it for routine state updates. It discards structural sharing, so every reference-equality check downstream reports a change.
Common Mistakes When Weighing Trade-offs
- Optimizing before measuring. Spread copies of small objects are rarely the bottleneck. Profile first.
- Deep cloning "to be safe". It feels defensive, but it costs a full traversal and breaks memoization everywhere.
- Mixing styles inside one state tree. Half Immutable.js and half plain objects means conversion code at every boundary and bugs where the two meet.
- Forgetting that freezing is shallow. A frozen top level with mutable children gives you false confidence.
- Treating
readonlytypes as runtime protection. TypeScript removes them at compile time. JavaScript callers and type casts can still mutate the data.
Exercise
A function builds a lookup table from 50,000 records using records.reduce((acc, r) => ({ ...acc, [r.id]: r }), {}). It is slow. A teammate says switching to a for loop that assigns acc[r.id] = r would "break immutability". Are they right, and what is the cost difference?
Show answer
They are not right. The accumulator is created inside the function and nothing else references it until it is returned, so mutating it changes no shared data. The spread version copies the whole accumulator on every iteration, which is O(n²) work, about 1.25 billion property copies for 50,000 records. The loop, or Object.fromEntries(records.map(r => [r.id, r])), is O(n). The input records are untouched in every version.
Exercise
A React component wrapped in memo re-renders on every store update, even when its todo list has not changed. The reducer handles "remove todo" with state.todos.filter(t => t.id !== action.id) and always returns { ...state, todos: filtered }. Why does it re-render, and how do you fix it?
Show answer
filter always returns a new array, even when no element was removed, so todos gets a new reference on every remove action. Reference equality then reports a change. Fix it by returning the original state when nothing was removed, for example by checking filtered.length === state.todos.length and returning state in that case. Writing the reducer with Immer also works, because produce returns the original object when the recipe makes no effective change.
Exercise
Your team is choosing between Immer and Immutable.js for an app whose state is a few hundred keys of nested settings and a list of about 200 items. Which would you choose, and why?
Show answer
Immer. The state is small, so the O(log n) updates of persistent structures bring no real benefit. Immutable.js would add conversion costs, a non-standard API, and lock-in. Immer keeps plain objects that work with every library, removes nested-spread boilerplate, preserves structural sharing for reference-equality checks, and auto-freezes results to catch mutation bugs.