ai js change prototype slow (2026-09-12)
ai js change prototype slow
in JavaScript, why is changing a object's parent slow, how slow
(ai answer)
Changing an object’s parent in JavaScript almost always means changing its prototype ([[Prototype]]) with Object.setPrototypeOf(obj, newParent) or obj.__proto__ = newParent. That is slow, and MDN explicitly warns against it.
Why it’s slow
Modern engines (V8, SpiderMonkey, JavaScriptCore) optimize property access with:
- Hidden classes / shapes / maps — each object has a compact description of its layout and prototype.
- Inline caches (ICs) — “the last time I looked up
.xon this kind of object, it was at offset N on this prototype.” - Type feedback and JIT assumptions — compiled code assumes the prototype chain is stable.
Changing the prototype:
- Invalidates the object’s hidden class.
- Flushes inline caches that pointed at the old chain.
- Can deoptimize functions that already optimized accesses on that object (or on objects that share the same shape).
- Forces the engine to walk and notify other type-inference data that depended on the old prototype.
The cost is not just the setPrototypeOf call itself. Any later code that touches the mutated object (or objects that shared optimizations with it) can stay slower.
Property lookup on a stable prototype chain is cheap because engines cache the path. After a mutation they often fall back toward slower generic lookup.
How slow?
There is no single number — it depends on engine, how hot the code is, and how many objects/functions are affected.
Typical picture:
- A one-off change on a cold object: often microseconds; you may not notice.
- The same change in a hot loop, or on objects that optimized methods already use: tens to hundreds of times slower subsequent property access until (or unless) the engine re-optimizes.
- The mutation itself is also more expensive than creating a new object with
Object.create(desiredProto).
MDN’s wording is deliberate: it is “a very slow operation in every browser and JavaScript engine,” and the damage “may extend to any code that has access to any object whose [[Prototype]] has been altered.”
What to do instead
Set the prototype once at creation time:
const obj = Object.create(desiredParent); // or const obj = { __proto__: desiredParent, ...ownProps };
Do not mutate an existing object’s parent after other code has already seen it.
If you meant DOM parent (appendChild / moving a node), that is a different cost: layout, style recalc, and possible reflow — also expensive, but for different reasons. The classic “changing an object’s parent is slow” warning in JS is about the prototype.