Sub topic 14
Choosing an Approach: Performance and Design Trade-offs
This chapter assumes you have worked through the earlier techniques: spread copies, non-mutating array methods, nested updates, Object.freeze, structuredClone, structural sharing, reference equality, Immer, and Immutable.js. Here the question is which one to use for a given job.
The cost model
Every immutable update allocates memory. The questions that matter are how much you copy and how often you do it.
| Approach | Copy cost per update | Strengths | Weak spots |
|---|---|---|---|
| Spread and array methods | Copies only the path that changed | No dependencies, plain objects, fast for small and medium state | Deep paths make the code verbose and easy to get wrong |
| `structuredClone` | Copies the whole value | Gives a fully independent snapshot | Slow on large data; drops functions and class prototypes |
| `Object.freeze` | None; it only enforces | Catches accidental writes | Shallow unless applied recursively; adds a walk of the object |
| Immer | Copies the changed path, using proxies | Reads like mutating code and keeps structural sharing | Proxy overhead, an extra dependency, drafts can be misused |
| Immutable.js | Small, using persistent tries | Efficient on very large collections | Its own API, plus `toJS()` conversion costs at boundaries |
A common performance trap
Copying inside a loop turns linear work into quadratic work. This pattern often appears in reduce calls:
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i, name: `item${i}` }));
// O(n^2): every step copies the whole accumulator
console.time('spread in reduce');
const slow = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});
console.timeEnd('spread in reduce');
// O(n): mutate an object that nobody else can see yet
console.time('local mutation');
function indexById(list) {
const index = {};
for (const item of list) {
index[item.id] = item;
}
return index;
}
const fast = indexById(items);
console.timeEnd('local mutation');
console.log(Object.keys(slow).length === Object.keys(fast).length); // trueindexById is still pure from the caller's point of view. It creates index, fills it, and returns it, and no other code ever sees a half-built version. Immutability matters for values that are shared. Mutating a value you just created, before anyone else holds a reference to it, is safe.
Design considerations
Performance is rarely the deciding factor. These usually matter more:
- Team familiarity. Spread syntax and
map/filterare plain JavaScript that every developer can read. Immer is easy to learn. Immutable.js asks everyone to learn a separate collection API. - Interop. Libraries, JSON, and the DOM expect plain objects. Immutable.js values have to be converted at every boundary, and each conversion costs time and allocations.
- Change detection. Frameworks that compare references, such as React's memoization or Redux selectors, need structural sharing. A full
structuredCloneon every update gives every object a new reference, so every comparison reports a change and memoization never skips work. - Safety. Freezing in development catches bugs early. Immer already auto-freezes the state it produces. Many teams skip deep freezing in production builds to avoid the extra cost.
A decision path
Start with plain spread and the copying array methods. Add Immer when nested updates start to clutter your code. Use Immutable.js only after profiling shows that copying large collections is a real bottleneck.
Exercise
A Redux reducer handles an "update profile" action by calling structuredClone on the entire state and then changing one field. The app becomes slow, and memoized components re-render on every action. Explain both problems and suggest a fix.
Show answer
structuredClone copies the whole state tree on every action, so each update costs time proportional to the size of the state. It also gives every nested object a new reference, so reference-equality checks report every branch as changed and memoized components re-render. The fix is to copy only the changed path, either with nested spread (spread the state, then the profile, then set the field) or with Immer's produce. Unchanged branches then keep their references.
Exercise
Is it wrong to use a for loop that assigns properties to a new object inside a function that builds a lookup table?
Show answer
No. The object is created inside the function, and nothing else references it until it is returned, so mutating it cannot affect shared data. This approach is also O(n), while spreading the accumulator on each step of reduce is O(n^2).