Sub topic 2
Running Bytecode in an Interpreter
This chapter assumes you can write JavaScript functions and loops, run scripts with Node.js from the command line, and know roughly how compiled code differs from interpreted code. It also builds on the previous chapter: the engine has parsed your source and produced bytecode. Here we look at what happens when that bytecode runs, using V8's interpreter, Ignition, as the example.
Why engines start with an interpreter
An interpreter is a program that reads instructions one at a time and carries each one out. It never produces machine code for your function. Starting there sounds slow, so it is worth asking why every major JavaScript engine does it.
Most JavaScript on a page or in a Node.js process runs once or only a few times. Module setup, configuration code, and event handlers that fire once fall in this group. Compiling all of that to optimized machine code would cost more time and memory than running it. An interpreter can start executing almost immediately after bytecode generation, and bytecode is compact. In V8, the bytecode for a function is typically several times smaller than the baseline machine code for it. That matters on phones and in processes with thousands of functions.
The interpreter has a second job that matters just as much. While it runs your code, it records what actually happened: which object shapes reached a property access, which types reached an addition. Later chapters cover this type feedback and how the optimizing compilers use it. For now, keep in mind that the interpreter both executes code and collects the evidence the faster tiers depend on.
Tree-walking versus bytecode interpreters
Early JavaScript engines walked the abstract syntax tree (AST) directly. A bytecode interpreter runs a flat list of simple instructions instead.
| Approach | How it executes | Strengths | Weaknesses |
|---|---|---|---|
| Tree-walking interpreter | Recursively visits AST nodes | Simple to build | Pointer-chasing, poor cache use, large memory footprint |
| Bytecode interpreter | Loops over a compact instruction array | Small, cache-friendly, easy to attach feedback slots | Still pays a dispatch cost per instruction |
| Machine code (JIT) | CPU runs native instructions | Fastest at peak | Compile time and memory cost |
V8 used to skip interpretation entirely and compile everything with a quick baseline compiler. Ignition replaced that approach in 2016 and 2017, mainly to cut memory use.
Ignition's machine model: registers and an accumulator
Ignition is a register machine with an accumulator. Each function's stack frame holds a register file. That is a set of slots named r0, r1, and so on for local variables and temporaries, plus a0, a1, and so on for parameters. One special register, the accumulator, is an implicit input and output for most instructions.
Because the accumulator is implicit, most bytecodes name only one operand. That keeps instructions short. Here is a small function:
// add.js
function add(a, b) {
return a + b;
}
console.log(add(2, 3));You can ask Node.js to print the bytecode V8 generates for it:
node --print-bytecode --print-bytecode-filter=add add.jsThe core of the output looks like this. The exact formatting and offsets vary between Node.js versions:
0 : Ldar a1
2 : Add a0, [0]
4 : ReturnEach instruction does one thing:
Ldar a1loads parameterbinto the accumulator.Add a0, [0]computesa0 + accumulator, which isa + bin source order, and leaves the result in the accumulator. The[0]is a feedback slot index. The interpreter records what kinds of values it saw here.Returnreturns whatever is in the accumulator.
The Add bytecode is generic. It has to handle numbers, strings, objects with valueOf, BigInts, and every other case JavaScript allows. The interpreter cannot assume anything, so each generic operation checks the types it receives on every execution.
The dispatch loop
Conceptually, an interpreter is a loop: fetch the next bytecode, jump to the code that handles it, run that handler, repeat.
Ignition does not use a central switch statement. Each bytecode has a handler, a small piece of machine code. At the end, each handler looks up the next bytecode in a dispatch table and jumps straight to that handler. This is called threaded dispatch. It avoids returning to a central loop, and it gives the CPU's branch predictor a separate indirect jump per handler, which it predicts better.
V8 does not write these handlers by hand in assembly. They are written in a portable internal language, the CodeStubAssembler, and compiled by TurboFan's backend when V8 itself is built. The finished handlers ship inside V8's startup snapshot. So the interpreter is fast machine code. What it runs, your bytecode, is the part that is interpreted.
A loop in bytecode
Loops show where interpreter time goes. Consider:
// sum.js
function sum(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
console.log(sum([1, 2, 3, 4]));node --print-bytecode --print-bytecode-filter=sum sum.jsThe listing below is abbreviated and illustrative. Opcode names changed across V8 versions, for example LdaNamedProperty became GetNamedProperty:
LdaZero
Star0 ; total = 0
LdaZero
Star1 ; i = 0
loop:
GetNamedProperty a0, [0] ; arr.length
TestLessThan r1, [2] ; i < arr.length
JumpIfFalse exit
Ldar r1
GetKeyedProperty a0, [3] ; arr[i]
Add r0, [5] ; total + arr[i]
Star0
Ldar r1
Inc [6] ; i++
Star1
JumpLoop loop, [7]
exit:
Ldar r0
ReturnThe listing shows three things.
- Every iteration runs about a dozen handlers. Each one pays the dispatch cost and repeats its generic type checks.
- Property accesses such as
arr.lengthandarr[i]carry feedback slots. Inline caches, covered later, attach to these slots. JumpLoopdoes more than jump backward. It is also where V8 checks whether the loop has become hot enough to move to a faster tier in the middle of a running loop. This is called on-stack replacement.
Short opcodes such as Star0 are compact forms of Star r0. V8 adds them for the most common registers to save bytes.
What the interpreter costs
Interpretation trades speed for flexibility in predictable ways:
- Dispatch overhead. Every bytecode costs at least a table lookup and an indirect jump, even trivial ones such as
Star0. - Memory traffic. Registers live in the stack frame in memory, not in CPU registers, so values move back and forth constantly.
- Generic operations.
Addcannot know that its inputs are always small integers, so it checks every time.
For cold code these costs do not matter. For a hot loop they add up, and that is why the later tiers exist.
Edge cases worth knowing
- Bytecode flushing. If a function has not run for a while, V8 can throw away its bytecode during garbage collection to free memory. It regenerates the bytecode if the function is called again. This rarely matters, but it explains small, irregular warm-up costs in long-running processes.
- Lazy feedback allocation. The feedback storage for a function is allocated only after the function has run a few times. Code that runs once never pays for it.
- Debugging. Ignition's bytecode keeps a mapping back to source positions. That mapping is how stack traces and breakpoints work even when no machine code exists.
Exercises
Exercise
In the bytecode Ldar a1; Add a0, [0]; Return for function add(a, b) { return a + b; }, why does Add name only one register, and what is [0]?
Show answer
The accumulator is an implicit operand. It already holds b, so Add only needs to name a0 and writes the result back to the accumulator. [0] is the index of a feedback slot where the interpreter records the types it saw at this addition, for later use by the optimizing tiers.
Exercise
You run node --print-bytecode --print-bytecode-filter=helper app.js and see no output for helper, even though it is defined in app.js. What is the most likely reason?
Show answer
helper was never called during the run. V8 compiles functions to bytecode lazily on their first call, so an uncalled function has no bytecode to print.
Exercise
Name two costs a bytecode interpreter pays on each iteration of a hot loop that optimized machine code can avoid.
Show answer
Any two of the following: the per-instruction dispatch (a table lookup and an indirect jump for every bytecode), moving values between the in-memory register file and the accumulator, and type checks inside generic operations such as Add and property loads that run on every execution.