« All posts

The Hidden Performance Cost of Object Spread in JavaScript

A deep dive into the real performance cost of JavaScript object spread, the reduce anti-pattern, and when tools like Immer make more sense.

The `{...state, key: value}` pattern found everywhere in React, Redux and Vue codebases feels free, but under the hood the JS engine copies every property of the source object into a new one each time. For small objects this is negligible, but for large objects or repeated spreads inside reduce (e.g., converting an array to a lookup map by id), the total work can silently degrade from O(n) to O(n²), since each iteration re-copies everything accumulated so far.

A plain for-of loop avoids this by mutating a single object in one pass. React's reliance on reference equality for re-renders explains why spread became so popular—a new object reference signals a change instantly—but deeply nested state updates turn spread into unreadable, allocation-heavy code that adds garbage collection pressure. Libraries like Immer, or better state normalization, offer more scalable alternatives for these cases.

The real takeaway is that object spread is neither inherently slow nor inherently fast—it depends on object size, update frequency, and nesting depth. Understanding this tradeoff lets engineers make deliberate choices instead of blindly copying objects everywhere.

» SourceDev.to