Interpreters & Virtual Machines

Tree-walking interpreters, bytecode compilers, stack vs register VMs, the dispatch loop and its optimisations, JIT compilation tiers, inline caches, and how CPython, the JVM, V8 and Lua are built.

Advanced 4 min readLesson 7 of 8 Interview Q&A

Not every language is compiled to machine code ahead of time. Interpreters execute programs directly; virtual machines execute a portable instruction set (bytecode) in software, and often JIT-compile the hot parts.

Tree-walking interpreters

The simplest approach: parse to an AST, then recursively evaluate each node.

Python
def evaluate(node, env):
    match node:
        case Num(v):               return v
        case Var(name):            return env[name]
        case Binary("+", l, r):    return evaluate(l, env) + evaluate(r, env)
        case Binary("*", l, r):    return evaluate(l, env) * evaluate(r, env)
        case Let(name, value):     env[name] = evaluate(value, env)
        case If(cond, then, els):  return evaluate(then if evaluate(cond, env) else els, env)
        case While(cond, body):
            while evaluate(cond, env):
                evaluate(body, env)

Easy to write — a complete interpreter for a small language fits in a few hundred lines — but slow: pointer-chasing through tree nodes, recursion overhead and poor cache locality. Fine for config languages, templates and prototypes.

Bytecode VMs

Faster interpreters first compile the AST to bytecode — a compact, linear sequence of simple instructions — and then run it in a tight loop.

Source:   x = a + b * 2

Stack bytecode (CPython-style):          Register bytecode (Lua-style, a in r0, b in r1):
  LOAD_NAME   a                            MUL  r2, r1, K(2)    ; r2 = b * 2
  LOAD_NAME   b                            ADD  r3, r0, r2      ; r3 = a + r2  (x)
  LOAD_CONST  2
  BINARY_OP   *
  BINARY_OP   +
  STORE_NAME  x

Try it in Python: import dis; dis.dis("x = a + b * 2") (CPython internals).

Stack vs register machines

Stack VMRegister VM
OperandsImplicit, on an operand stackExplicit virtual registers
InstructionsMore, but smallerFewer, but larger
CompilerSimpler to generate code forNeeds register assignment
ExamplesJVM, CPython, .NET CLR, WebAssemblyLua 5, Dalvik (Android), V8 Ignition (register + accumulator)

Register VMs execute fewer instructions (less dispatch overhead) and are generally a bit faster; stack VMs produce compact, easily verified code.

The dispatch loop

The heart of a VM is a loop that fetches, decodes and executes instructions:

C
for (;;) {
    uint8_t op = *ip++;
    switch (op) {
        case OP_CONST: push(constants[*ip++]); break;
        case OP_ADD:  { Value b = pop(), a = pop(); push(a + b); break; }
        case OP_JUMP_IF_FALSE: { uint16_t off = read16(ip); ip += 2; if (!truthy(peek())) ip += off; break; }
        case OP_RETURN: return pop();
    }
}

Dispatch overhead (the branch on op) dominates simple instructions. Tricks:

  • Computed goto / threaded code: each handler jumps directly to the next handler (goto *table[*ip++]), giving the CPU's branch predictor one indirect branch per handler instead of one shared branch. CPython and Ruby use this.
  • Superinstructions: fuse common sequences (LOAD_FAST + LOAD_FAST) into one opcode.
  • Quickening / specialisation: rewrite a generic instruction into a type-specific one after observing its operands (CPython 3.11's specialising adaptive interpreter: BINARY_OP → BINARY_OP_ADD_INT).

JIT compilation

A just-in-time compiler compiles bytecode to machine code at runtime, for code that runs often enough to pay back the compile cost. Because it runs alongside the program, a JIT can use information an AOT compiler never sees: actual types, hot paths, which branches are taken.

Interpreterstart immediately; collect profiles (types, counts)all codeBaseline JITquick compile, few optimisationswarm codeOptimising JITspeculative inlining, type specialisation, escape analysishot codeDeoptimisationa speculation failed: bail back to the interpreterrare
VMTiers
HotSpot JVMInterpreter → C1 (fast) → C2 (optimising) — JIT compilation
V8Ignition (interpreter) → Sparkplug (baseline) → Maglev (mid-tier) → TurboFan (optimising) — V8 internals
.NETTiered compilation: tier 0 → tier 1 with PGO
PyPyA tracing JIT: records hot loop traces and compiles them
LuaJITFast interpreter + tracing JIT
CPython 3.13+Experimental copy-and-patch JIT

Speculation and deoptimisation

Dynamic languages don't fix types, so the optimising JIT speculates based on profiles ("x has always been a small integer here") and inserts cheap guards. If a guard fails, the VM deoptimises: reconstructs the interpreter state and continues there, perhaps recompiling later with the new information.

Inline caches and hidden classes

Property access in dynamic languages (obj.x) would require a hash lookup each time. VMs give objects hidden classes (shapes) describing their layout, and each access site keeps an inline cache — "last time, the shape was S and x was at offset 16". If the shape matches, the access is a single load. Sites that see one shape are monomorphic (fast); many shapes make them megamorphic (slow).

Other VM components

A language VM is more than an execution loop:

  • Memory management: allocation and garbage collection.
  • Object model: value representation (tagged pointers, NaN-boxing), strings, closures.
  • Class loading and linking (Class loading), bytecode verification.
  • Runtime services: exceptions, threads, reflection, debugging and profiling hooks, a foreign function interface.
Key takeaways
  • Tree-walking interpreters evaluate the AST directly: simple, slow.
  • Bytecode VMs compile to compact instructions and run a dispatch loop; stack VMs are simpler, register VMs execute fewer instructions.
  • Threaded dispatch, superinstructions and quickening speed up interpreters.
  • JITs compile hot code at runtime in tiers, speculating on observed types and deoptimising when wrong.
  • Hidden classes and inline caches make dynamic property access nearly as fast as static field access.
Interview questions
QWhy can a JIT compiler sometimes beat an ahead-of-time compiler?hard

A JIT sees the program actually running. It knows which types flow through each operation, which branches are hot, which virtual calls have a single receiver type, and which classes are loaded. It can speculatively inline and specialise on that information with cheap guards, deoptimising if assumptions break. An AOT compiler must generate code correct for every possible input unless given profile data (PGO). The costs are warm-up time, memory for compiled code, and compile work at runtime.