# What is a bytecode virtual machine?

> A bytecode VM compiles a program to a compact instruction array and runs it in a loop. Stack-based VMs, how clox works, and why it beats tree-walking.

**Bytecode virtual machine**: A bytecode virtual machine runs a program that has been compiled into a compact sequence of simple instructions (bytecode), decoding and executing one instruction at a time in a loop.

A **bytecode virtual machine** runs programs compiled into **bytecode**: a dense array of one-byte opcodes and operands, like a made-up machine language. A loop reads each instruction and does what it says. [clox](https://cracked.guide/glossary/clox) is one; so are the core interpreters of many popular dynamic languages.

## Stack-based VMs

clox is **stack-based**: instructions take their operands from a value stack and push results back. `1 + 2` compiles to `OP_CONSTANT 1`, `OP_CONSTANT 2`, `OP_ADD`. The alternative, a **register-based** VM, names its operands explicitly, which means fewer instructions but bigger ones. The book picks a stack VM because it is simpler to compile for.

## Why it is faster than a tree-walker

The instructions sit next to each other in memory, so the CPU cache works for you, and the dispatch is a single `switch` in a tight loop instead of a virtual call per tree node. Crafting Interpreters builds one from [chapter 14](https://cracked.guide/guide/ci-14) on and measures the difference.

## Questions

### Is bytecode the same as machine code?

No. Machine code runs on real hardware. Bytecode runs on a virtual machine, which is itself a program.

### Is a bytecode VM a compiler?

It usually comes with one: a compiler turns source into bytecode, then the VM runs it. clox does both in one pass.

---

Source: https://cracked.guide/glossary/bytecode-vm
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
