JS RuntimeBaseline · Widely

V8 Hidden Classes (Shapes) and Inline Caches

Mental Model

V8 assigns every object a Hidden Class (internal Map) describing its property memory offsets. When objects share the same shape, obj.x compiles to a direct constant-offset memory read via an Inline Cache (IC).

Interactive Simulator

Inline Cache Evolution in V8

Observe the transition from Monomorphic to Megamorphic when a function receives heterogeneous Shapes.

Step 1 / 3: 1. Monomorphic (1 Shape)

getX({ x: 1, y: 2 }) caches Shape_AB and reads offset +0 directly.

function getX(p) { return p.x; }
Internal State / Memory
icState
MONOMORPHIC
cachedShapes
1
lookupCost
1 pointer comparison

Under the Hood

An Inline Cache works like a keyed-entry warehouse dock: if every pallet arrives in the same box layout (Monomorphic), the forklift grabs slot #2 blindfolded; if five different box layouts arrive (Megamorphic), the worker stops to read the manifest hash table every time.

  1. Shape Transitions: Creating { a: 1, b: 2 } builds a shape chain Empty -> +a (offset 0) -> +b (offset 1).
  2. Monomorphic Inline Cache: At a call site getX(obj) inside a hot Event Loop task, V8 caches the expected Shape and exact offset; a single pointer comparison suffices.
  3. Polymorphic vs Megamorphic: Beyond 4 distinct Shapes at the same call site, the IC turns megamorphic and falls back to an expensive global hash lookup.
JS
// Monomorphic: both objects follow the exact same transition chain
function Point(x, y) {
  this.x = x;
  this.y = y;
}
const p1 = new Point(1, 2);
const p2 = new Point(3, 4);

// Megamorphic trap: different property orders create distinct Shapes
const bad = { y: 4, x: 3 };

Problem Genealogy

  • 1995 (Naive Interpreters): Every obj.prop access performed a dynamic dictionary lookup.
  • 2008 (V8 Hidden Classes & Crankshaft): Imported Self/Smalltalk techniques to compile property reads into direct machine instructions.
  • 2017+ (Ignition + Sparkplug + Maglev + TurboFan): Multi-tier JIT compilation pipeline driven by Inline Cache feedback, and invalidated the moment someone mutates object shapes in a hot loop.

Production Pitfalls

Production Pitfall
  • Inconsistent property initialization order: Creating { a: 1, b: 2 } in one branch and { b: 2, a: 1 } in another produces two incompatible Shapes, degrading Fine-Grained Signals or parser hot paths.
  • delete obj.prop: Deleting a property often downgrades the object to dictionary mode (Slow Properties), breaking JIT optimizations; assign undefined instead.
When Not to Use
  • When not to use manual Shape optimization: For configuration objects read once at startup, readability comes first; enforce strict Shapes only in hot loops (parsers, renderers, per-frame math), and keep Proxy Traps out of those hot loops.

Connections & Logical Next Steps

JS RuntimeV8 Hidden Classes (Shapes) and Inline Caches
What This Unlocks
Leaf concept

Mechanical Comparisons