javascript / expert
Snippet
Optimizing Property Access via Monomorphic Shapes
V8 uses Hidden Classes and Inline Caches (IC) to optimize property lookups. A function is 'monomorphic' if it always receives objects with the same internal shape. When shapes vary (polymorphism), V8 must perform complex lookups, eventually falling back to 'megamorphism', which significantly degrades performance.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function calculate(point) {return point.x + point.y;}// Monomorphic: Only one shape seenconst p1 = { x: 10, y: 20 };calculate(p1);// Polymorphic: Multiple shapesconst p2 = { x: 30, y: 40, z: 50 };calculate(p2);// Megamorphic: Too many shapes (V8 stops caching)const p3 = { y: 10, x: 5 };calculate(p3);
nodejs
Breakdown
1
function calculate(point) {
The target function for V8's Inline Cache optimization.
2
const p1 = { x: 10, y: 20 };
Creates a hidden class with properties 'x' then 'y' in that order.
3
const p3 = { y: 10, x: 5 };
A different hidden class because the property definition order changed.