Sub topic 21
Performance: Why Changing Prototypes at Runtime Is Discouraged
This chapter assumes you know how the prototype chain resolves property lookups, how Object.create and Object.getPrototypeOf work, and how classes and constructor functions set up prototype links. You don't need any knowledge of engine internals. The chapter explains what engines do with prototypes in general terms and why that makes Object.setPrototypeOf and assignments to __proto__ expensive.
The Rule in One Sentence
Set an object's prototype when you create it, and leave it alone afterward. MDN's documentation for Object.setPrototypeOf says that changing an object's [[Prototype]] is a very slow operation in every engine. The slowdown is not limited to the line that makes the change. It can spread to any code that later touches the modified object.
How Engines Make Property Lookup Fast
The spec describes lookup as a walk: check the object's own properties, then its prototype, then that object's prototype, until a match turns up or the chain reaches null. Doing that walk on every access would be slow, so engines avoid it with two techniques.
Shapes (Hidden Classes)
The engine groups objects by their layout. A shape records which properties an object has, the order they were added in, where each value is stored, and which object is the prototype. V8 calls these "maps", SpiderMonkey calls them "shapes", and JavaScriptCore calls them "structures". Two objects created the same way, with the same prototype, share one shape.
Inline Caches
Every property access in your code, such as point.x or rex.speak(), gets a small cache. The first time that access runs, the engine does the full lookup. Then it records the shape it saw and where the property turned up. On later runs it only checks whether the object has the same shape. If it does, the engine reads the value straight from the remembered location without walking the chain.
For an inherited method, the cache records "for objects of this shape, speak lives on this prototype object." That shortcut is only safe while the prototype chain keeps its structure. The engine therefore attaches a validity check to the chain, and certain changes to the prototypes invalidate it.
What setPrototypeOf Breaks
The prototype is part of an object's shape, so calling Object.setPrototypeOf(obj, other) gives obj a new shape. That has several consequences:
- Cache misses. Every inline cache that had seen
obj's old shape now misses forobj. If one access site sees many shapes, its cache becomes polymorphic (it holds several entries) or megamorphic (it gives up and falls back to a generic slow lookup). - Lost optimizations. Optimized machine code that assumed the old layout may be thrown away (deoptimized) and compiled again later.
- Unusual objects. Some engines move an object into a slower dictionary-style representation after its prototype changes. Code that touches that object stays slower long after the change.
- Damage to the target. When an object becomes a prototype, engines often restructure it so it works well as one. Turning a busy object into a prototype at runtime forces that work at a bad moment.
None of this is visible in the language semantics. Your program still produces correct results. It just runs slower, often in code that is far away from the line that caused it.
Creating with the Right Prototype Instead
The fix is almost always to choose the prototype at creation time. These patterns all set the link once, before the object is used:
const base = {
describe() {
return `${this.name} (${this.kind})`;
}
};
// Discouraged: create, then re-link
const slow = { name: 'Widget', kind: 'tool' };
Object.setPrototypeOf(slow, base);
// Preferred: link at creation
const fast = Object.create(base);
fast.name = 'Widget';
fast.kind = 'tool';
// Also fine: __proto__ inside an object literal sets the prototype at creation
const alsoFast = { __proto__: base, name: 'Gadget', kind: 'tool' };
// Also fine: classes link instances through new
class Item {
constructor(name, kind) {
this.name = name;
this.kind = kind;
}
describe() {
return `${this.name} (${this.kind})`;
}
}
const viaClass = new Item('Lever', 'tool');
console.log(slow.describe()); // "Widget (tool)"
console.log(fast.describe()); // "Widget (tool)"
console.log(alsoFast.describe()); // "Gadget (tool)"
console.log(viaClass.describe()); // "Lever (tool)"Measuring It Yourself
Microbenchmarks are noisy, and every engine handles them differently, so look at the relative difference rather than the exact numbers. The script below runs in Node.js 16 or later, or in a browser console:
const proto = {
value() {
return this.n * 2;
}
};
function makeLinkedLater(n) {
const o = { n };
Object.setPrototypeOf(o, proto);
return o;
}
function makeLinkedAtCreation(n) {
const o = Object.create(proto);
o.n = n;
return o;
}
function run(label, factory) {
const start = performance.now();
let sum = 0;
for (let i = 0; i < 1_000_000; i++) {
sum += factory(i).value();
}
const ms = (performance.now() - start).toFixed(1);
console.log(`${label}: ${ms} ms (sum ${sum})`);
}
run('setPrototypeOf after creation', makeLinkedLater);
run('Object.create at creation ', makeLinkedAtCreation);On most engines the setPrototypeOf version runs noticeably slower. The size of the gap depends on the engine version and on whether the optimizer handles this particular loop well. Treat any one result as a hint, and profile your real code before you rewrite it.
Related Costs Worth Knowing
| Operation | Cost profile | Advice |
|---|---|---|
| `Object.create(proto)` | Cheap, one-time link | Preferred way to pick a prototype |
| `{ __proto__: proto, ... }` literal | Cheap, set at creation | Fine to use |
| `Object.setPrototypeOf(obj, p)` on a live object | Expensive, spreads to later accesses | Avoid in hot paths. Re-create the object instead |
| `obj.__proto__ = p` | Same as `setPrototypeOf` | Avoid. It is also a legacy feature |
| Adding methods to a prototype at startup | Cheap | Normal practice, as with mixins |
| Adding or deleting prototype methods while code is running | Invalidates caches for that chain | Finish setup before heavy use |
| Changing built-in prototypes such as `Array.prototype` | Affects every array access site | Don't do it (see the earlier chapter) |
When setPrototypeOf Is Acceptable
Some code really does need to change a prototype after creation: test utilities, polyfills, and one-time setup code that runs before anything heavy happens. In those cases the cost is paid once and doesn't matter. The rule is about hot paths, meaning code that runs many times, such as request handlers, render loops, and tight data-processing loops.
Exercise
A data loader parses JSON into plain objects and then calls Object.setPrototypeOf(record, Record.prototype) on each one so the records get methods. Explain why this is slow and rewrite the approach.
Show answer
Each setPrototypeOf call gives the record a new shape after it was already built. Inline caches that saw the plain-object shape miss, some engines switch the object to a slower representation, and every later method call on the records can be slower. Build the object with the right prototype from the start: const rec = Object.assign(Object.create(Record.prototype), parsed);, or better, new Record(parsed) with a constructor that copies the fields.
Exercise
Which of these sets the prototype at creation time and is therefore cheap: (a) const o = { __proto__: base }, (b) o.__proto__ = base, (c) Object.create(base), (d) Object.setPrototypeOf({}, base)?
Show answer
(a) and (c). Option (b) uses the legacy accessor, and (d) calls setPrototypeOf on an object that already exists. Both change the link after creation. In (d) the object is new and has never been used, so the cost is small, but (c) is still the clear and recommended form.