javascript / expert
Snippet
Optimizing V8 Hidden Classes and Object Shapes
V8 uses 'Hidden Classes' to optimize property access. When objects share the same structure and initialization order, V8 can use Inline Caching (IC) to access properties at machine-code speeds. Adding properties dynamically or changing their order breaks this optimization, leading to slower 'dictionary mode' lookups.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
function Point(x, y) {this.x = x;this.y = y;}const p1 = new Point(1, 2);const p2 = new Point(3, 4);// Optimization: Keep property initialization order consistent// This ensures p1 and p2 share the same 'Hidden Class' (Shape)p2.z = 5; // p2 now transitions to a new shape, becoming 'polymorphic'
nodejs
Breakdown
1
this.x = x; this.y = y;
Initializes properties in a fixed order to create a stable hidden class.
2
p2.z = 5;
Forces a shape transition, making p2 no longer compatible with the optimized code for p1.