Sub topic 2
Shape Transitions and Why Property Order Matters
This chapter assumes you can write JavaScript objects and functions, run scripts with Node.js, and know that V8 gives every object a hidden class (V8 calls it a map).
Transition Chains
A hidden class records which properties an object has and where each one is stored. When you add a property, V8 does not edit the current hidden class. It moves the object to a new hidden class through a transition. V8 stores that transition, so later objects that add the same properties in the same order reuse the same chain.
The order of additions matters:
const p = { x: 1, y: 2 };
const q = { y: 2, x: 1 };
// Same properties, different insertion order:
// p and q end up with different hidden classes.Dictionary Mode
If you delete a property that was not the last one added, V8 usually gives up on the fixed layout. The object switches to dictionary mode, where properties are stored in a hash table. Lookups in a hash table are slower than reading from a fixed position.
// Run with: node --allow-natives-syntax dict.js
const o = { a: 1, b: 2 };
console.log(%HasFastProperties(o)); // true
delete o.a;
console.log(%HasFastProperties(o)); // falseInline Caches and Their States
Each property access in bytecode, such as o.x, has an inline cache (IC). The IC stores the hidden classes it has seen and the offset of x in each one. When the next object has a hidden class the IC already knows, V8 reads the value from that offset and skips the full lookup.
| State | Shapes seen | Cost |
|---|---|---|
| Monomorphic | 1 | One check, then a direct load |
| Polymorphic | 2 to 4 | A short list of checks |
| Megamorphic | More than 4 | Falls back to a slower generic lookup |
function getX(o) {
return o.x;
}
for (let i = 0; i < 100000; i++) getX({ x: i }); // monomorphic
getX({ x: 1, y: 2 }); // polymorphic
getX({ y: 2, x: 1 });
getX({ x: 1, z: 3 });Type Feedback
V8 stores IC states in a per-function feedback vector. Each slot in the vector records what an operation has actually seen: which shapes reached a property access, and which value types reached an operator such as +. The optimizing compilers read this feedback to decide what code to generate. Stable shapes produce clear feedback, and clear feedback lets the compiler make better optimization decisions.
Exercise
A function reads user.name from objects built by three different object literals: {name, age}, {age, name}, and {name, age, email}. What IC state does that access reach, and why?
Show answer
It becomes polymorphic. The three literals produce three hidden classes. The first two have the same keys but in a different order, and the third has an extra property. Three shapes is more than one and no more than four.