Sub topic 3
What Just-in-Time Compilation Means
This chapter assumes you can write and run JavaScript with Node.js. You should know the basic difference between a compiler, which translates a whole program to machine code before it runs, and an interpreter, which executes a program step by step. You should also have read the previous chapters: V8 parses source into an abstract syntax tree (AST), turns that tree into bytecode, and its Ignition interpreter runs the bytecode.
Here you will learn what "just-in-time" (JIT) compilation means, why JavaScript engines use it, what it costs, and how an engine decides which code is worth compiling. Later chapters cover the individual V8 tiers and the speculation they rely on.
The Problem JIT Compilation Solves
An interpreter is flexible and quick to start. Each bytecode instruction is handled by a small routine called a handler. The interpreter fetches an instruction, decodes it, jumps to its handler, and repeats. That loop adds overhead to every operation. A simple a + b costs a dispatch, a few loads from the interpreter's register file, a type check, and the addition itself.
Ahead-of-time (AOT) compilation, as C and Rust compilers do it, avoids that overhead by producing machine code before the program runs. JavaScript makes AOT hard for three reasons:
- Code arrives as source text over the network, and the user is waiting for the page to respond.
- Types are dynamic. Without running the code, a compiler cannot know whether
a + badds integers, adds floats, joins strings, or callsvalueOfon objects. - Most code in a typical page or package runs once or never. Compiling all of it fully would waste time and memory.
JIT compilation splits the difference. The engine starts by interpreting, watches what the program actually does, and compiles to machine code only the parts that run often, while the program is running.
The Three Execution Strategies Compared
| Strategy | When machine code is produced | Startup cost | Steady-state speed | Knowledge available to the compiler |
|---|---|---|---|---|
| Pure interpretation | Never | Very low | Slow | None needed |
| Ahead-of-time compilation | Before the program runs | High, paid by the developer or at install time | Fast | Static types and source only |
| Just-in-time compilation | During execution, for selected functions | Low at first, rising as code gets hot | Fast for hot code | Static source plus observed runtime behavior |
The last column is the key advantage of a JIT. It compiles after it has watched the code run, so it can optimize for the types and object shapes that actually appeared. An AOT compiler for a dynamic language has to produce code that handles every possibility.
Hot Code and the Cost Model
A JIT pays a cost to compile and hopes to earn it back through faster execution. A simple model makes the trade-off concrete. Suppose a function takes I microseconds per call when interpreted, C microseconds per call when compiled, and compilation costs K microseconds once. Compiling pays off after n calls when:
n * I > K + n * C
n > K / (I - C)If compiling costs 500 µs and saves 2 µs per call, the function must run more than 250 times before the compiled version is a net win. That is why engines look for hot code, meaning functions and loops that have already run many times. The past is a reasonable predictor of the future: a function called 1,000 times is likely to be called again.
V8 tracks hotness with a per-function budget. Ignition charges the budget as the function executes, roughly in proportion to the bytecode it runs, including on loop back-edges and returns. When the budget runs out, V8 checks whether the function should move to a faster tier. The exact thresholds change between V8 versions and you should not rely on them.
What Happens at Compile Time
When V8 decides to compile a function, the JIT reads the function's bytecode together with the runtime data collected for it, then emits machine instructions for the current CPU. The result is stored as a code object attached to the function. The next call jumps straight into that machine code.
Three details of this step matter in practice.
- Compilation can run on a background thread. V8's optimizing compilers do most of their work off the main thread, so JavaScript keeps running in the interpreter while the faster code is built. The main thread only steps in at the start and to install the finished code.
- Machine code needs executable memory. The JIT writes instructions into memory and then marks that memory executable. Security hardening usually keeps such pages from being writable and executable at once ("W^X"), so the engine switches page permissions or uses a dedicated mapping.
- Compiled code can be thrown away. Machine code is a cache, and the bytecode stays the source of truth. If compiled code becomes invalid or memory is tight, the engine can discard it and fall back to bytecode. A later chapter covers this process, called deoptimization.
Seeing the JIT's Effect
You can measure the JIT by turning it off. Node accepts V8's --jitless flag, which forbids allocating executable memory at runtime. Only the interpreter runs, so V8 cannot generate any machine code at runtime.
Save this as jit-demo.js:
function sumOfSquares(n) {
let total = 0;
for (let i = 0; i < n; i++) {
total += i * i;
}
return total;
}
function timeRound(label, n) {
const start = performance.now();
const result = sumOfSquares(n);
const ms = performance.now() - start;
console.log(`${label}: ${ms.toFixed(2)} ms (result ${result})`);
}
for (let round = 1; round <= 5; round++) {
timeRound(`round ${round}`, 5_000_000);
}Run it both ways:
node jit-demo.js
node --jitless jit-demo.jsWith the JIT enabled, the first round is usually slower than the later ones. It starts in the interpreter, and OSR moves the loop into compiled code partway through. Later rounds call already-compiled code. With --jitless, every round runs at interpreter speed, and the total is often more than ten times slower. Your exact numbers depend on CPU, Node version, and system load.
Why a JIT Can Beat Static Compilation
A JIT that knows the actual runtime behavior can generate narrower code than a static compiler. If every call to sumOfSquares has passed a small integer, the compiler can emit plain integer multiply and add instructions, plus a cheap check that the input is still a small integer. Code written for any input would have to handle strings, objects, and BigInt everywhere. The engine records this runtime knowledge as type feedback, and later chapters explain it in detail.
The cost is that the compiled code is valid only while those observations hold. A JIT has to carry checks that detect when reality changes, along with a way to go back to slower, general code. That trade is the foundation of everything V8 does beyond interpretation.
Common Misconceptions
- "JIT means all JavaScript is compiled to machine code." It does not. Most functions in a large application never leave the interpreter, and that is by design.
- "Compiled code is always faster." Compiled code is faster per call, but compiling has its own cost. For code that runs only a few times, the time spent compiling outweighs the time saved.
- "The JIT compiles once and is done." A function can be compiled, discarded, and compiled again several times over a program's life as its behavior changes.
- "
--jitlessshows what JavaScript costs." It shows interpreter cost only. Use it to see the JIT's contribution, not as a model of production performance.
Exercise
A function costs 3 µs per call in the interpreter and 0.5 µs per call once compiled. Compiling it costs 400 µs. After roughly how many calls does compiling become a net win, and why does this suggest engines should not compile every function immediately?
Show answer
Compiling wins when n > 400 / (3 - 0.5) = 160 calls. Functions that run fewer than about 160 times would cost more to compile than they save, and most JavaScript runs only a few times. So engines wait for evidence that a function is hot before they pay to compile it.
Exercise
In jit-demo.js, the first round with the JIT enabled is slower than rounds 2 through 5, even though sumOfSquares is called only once in round 1. Which mechanism lets that single call speed up partway through, and why are later rounds faster still?
Show answer
On-stack replacement (OSR). The long loop exhausts the function's hotness budget, so V8 compiles the function and moves the running loop into machine code mid-execution. Round 1 still spends its early iterations in the interpreter and pays the compile cost. Later rounds call the already-compiled code from the start.