Skip to content

Lesson 8 of 9 · 25m

Virtual Machines: Representation and Performance

Why bytecode VMs are faster, where the time actually goes, and which optimizations are worth doing before a JIT is even a conversation.

Moving from tree walking to a VM is often sold as an automatic performance upgrade. It is not. The real win is replacing recursive dispatch over rich tree nodes with a tight loop over simple instructions. The real cost is owning representation decisions the tree interpreter could fudge.

Dispatch is only one cost center

A long if/elif dispatch chain is rarely the whole story. Time usually disappears into object allocation, dynamic type checks, hash-table variable lookups, and boxing every tiny integer as a heap object. Fast dispatch around expensive operations is still slow.

Values need a representation strategy

Start explicit and measure:

@dataclass(frozen=True)
class Obj:
    kind: str
    value: object

Mature runtimes often use tagged representations so small integers, booleans, and null avoid allocation. In a Python teaching VM you may not control that level, which is fine — the lesson is knowing where allocation pressure comes from, not pretending Python is C.

Variable access is the silent killer

env.values[name]   # hash lookup by string, every time

Compile locals into slots instead:

LOAD_LOCAL 0
LOAD_LOCAL 1
ADD

Now the VM indexes an array. Captured variables complicate this because they must outlive the frame that created them. A common model boxes captured variables into cells while non-captured locals stay in fast frame slots.

Measure with programs, not vibes

Keep a small benchmark suite: recursive arithmetic, tight numeric loops, string allocation, closure-heavy access, and call-heavy dispatch. Track wall time, allocations if available, and instruction counts. A change that halves instruction count but triples allocation may be a regression.

Optimize in an honest order: correct semantics, remove accidental host overhead, compile variable resolution to slots, reduce hot allocations, add constant folding, then consider inline caching or native compilation. A JIT is a large correctness and security surface, not a personality trait.

Field notes

  • Computed-goto dispatch matters in C-like hosts much more than in Python; measure before copying implementation folklore.
  • Preserve source spans through optimization. A fast implementation with worse errors feels worse than a slow one.
  • Keep the tree interpreter as a semantic oracle. Running the same corpus through both implementations catches optimizer bugs beautifully.
  • Never trust speed intuition across host languages. Allocation and call overhead dominate different designs.

Was this lesson helpful?

Sign in to rate