Hidden Classes & Inline Cache
Hidden Classes & Inline Cache
Section titled “Hidden Classes & Inline Cache”Hidden Classes (Shapes)
Section titled “Hidden Classes (Shapes)”Introduction
Section titled “Introduction”V8 assigns hidden classes (also called “shapes” or “maps”) to track object structure. Objects with the same properties share the same hidden class.
function Point(x, y) { this.x = x; // Hidden class: C0 this.y = y; // Hidden class: C1}
const p1 = new Point(1, 2); // Hidden class: C1const p2 = new Point(3, 4); // Shares C1 with p1Transition Chains
Section titled “Transition Chains”flowchart LR A["{}"]) -->|"add x"| B["{x}"] B -->|"add y"| C["{x, y}"] C -->|"add z"| D["{x, y, z}"]Performance Tips
Section titled “Performance Tips”// ✅ Good — consistent property orderfunction good(x, y) { this.x = x; this.y = y; }
// ❌ Bad — different property orders break sharingfunction bad(x, y) { if (x > y) { this.y = y; this.x = x; // y first } else { this.x = x; this.y = y; // x first }}Inline Cache (IC)
Section titled “Inline Cache (IC)”Introduction
Section titled “Introduction”Inline caching speeds up property access by caching the result of previous lookups.
function getX(obj) { return obj.x; // V8 caches the property offset}
// First call — V8 records the hidden class and offsetgetX({ x: 1 });
// Second call — if same hidden class, uses cached offset directlygetX({ x: 2 }); // Fast path 🚀
// Different hidden class — megamorphic (slower)getX({ x: 3, y: 4 }); // Different shapeIC States
Section titled “IC States”- Uninitialized: No data yet
- Monomorphic: One shape seen (fast)
- Polymorphic: 2-4 shapes seen
- Megamorphic: 5+ shapes seen (slow)
Summary
Section titled “Summary”- Hidden classes track object shapes
- Consistent property ordering = better performance
- Inline cache caches property access results
- Monomorphic access is fastest; megamorphic is slowest