JavaScript path · Under the hood · Topic 10 of 12

How V8 makes code fast

Not started

V8 (Chrome, Edge and Node) first turns your code into bytecode and interprets it with Ignition. Functions that run often are compiled by faster tiers, Sparkplug, Maglev and TurboFan, using what was learned about the shapes of the objects they saw. If those assumptions stop holding, the optimised code is thrown away and execution falls back to a slower tier.

Why it matters: Keeping object shapes consistent and functions predictable helps the optimiser; micro-tricks rarely do.

1

How it works

The explanation, with examples you can run.

The tiers

TierWhat it isTrade-off
IgnitionInterpreter for V8's bytecodeStarts instantly, runs slowest
SparkplugBaseline compiler: bytecode straight to machine codeFast to compile, no clever optimisation
MaglevMid-tier optimising compilerGood code, compiled quickly
TurboFanTop-tier optimising compilerBest code, most expensive to produce

While code runs, V8 records feedback: which shapes of objects reached each property access, which types each operation saw. The optimising tiers bet on that feedback staying true.

Shapes and inline caches

V8 gives objects with the same properties, added in the same order, the same hidden class (V8 calls it a map). A property access that only ever sees one shape can be compiled to a single memory load. Seeing many shapes at the same spot makes it slower.

// Same shape every time: fields set in the constructor, in the same order.class Point {  constructor(x, y) {    this.x = x    this.y = y  }} // Shapes that differ by creation order, or by fields added later, make the same code see many shapes.const a = { x: 1, y: 2 }const b = { y: 2, x: 1 } // a different shape from a

What actually helps

  • Initialise all fields in the constructor; avoid adding or delete-ing properties on hot objects later.
  • Keep a variable or array to one kind of value (don't mix numbers and strings in a hot array).
  • Measure before tuning: the Performance panel in DevTools, or node --cpu-prof, shows where time really goes.
2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.What does V8 run first when a function is called for the first time?
  2. 2.What usually makes V8 throw optimised code away?

0 of 2 right so far. Get all two to finish this topic.