The model
Bytecode is a compact instruction representation designed for a virtual machine rather than one physical processor. A VM fetches instructions, decodes operands, and updates execution state such as a stack, registers, frames, and heap. This layer can provide portability and runtime checks.
A concrete walk-through
A stack-based instruction sequence might push two constants, add the top values, and return the result. The VM’s instruction definitions specify operand widths, stack effects, and control-flow behavior. A verifier can reject malformed bytecode before execution if it proves stack and type constraints.
Costs and failure cases
Interpretation has dispatch overhead, while compiled native code may execute more directly but requires architecture-specific generation. Bytecode is only portable when runtimes agree on format and semantics. Sandboxing a VM also requires controlling native calls, memory, and resource consumption.
Check your understanding
For a stack VM, state the stack before and after an ADD instruction that consumes two numeric values. What invariant should a bytecode verifier enforce before this instruction executes?