An empty for loop's bytecode: 8 instructions, 56 steps, and why javac won't delete it
Most Java developers never read `javap` output, yet every loop they write is being laid out by `javac` with real trade-offs: the spec's layout is not what modern compilers emit, and an empty loop survives compilation because `javac` does no loop elimination, leaving that to the JIT. Knowing how the frame's two sizes, slot allocation, and branch forms are actually produced makes bytecode-level debugging and performance reasoning far less guesswork.
The JVM specification's classic `spin` example, an empty `for (i = 0; i < 10; i++)` loop, compiles to just 8 bytecode instructions: `iconst_0`, `istore_1`, `iload_1`, `bipush 10`, `if_icmpge`, `iinc`, `goto`, and `return`. The whole method executes in exactly 56 steps, with `locals=2` (slot 0 is `this`, slot 1 is `i`) and `stack=2` (the peak depth after `bipush 10` pushes the bound alongside `i`).
`javac 21` does not match the spec's illustrative listing. The spec places the condition test at the loop's bottom, using `goto 8` on entry and a self-looping `if_icmplt`, giving 4 instructions per iteration. `javac 21` tests first, using `if_icmpge 14` to exit and a separate `goto 2` to jump back, giving 5 per iteration. Both produce identical behavior — the spec trades one extra instruction on loop entry for one fewer per iteration, a trade-off Section 3.5 explains.
The article also walks through type variants: a `double` loop variable occupies two slots, has no `dinc` so `i++` needs four instructions, and has no `if_dcmplt` so comparisons go through `dcmpg` plus `iflt`; a `short` variable must be promoted to `int`, incremented, then truncated with `i2s`. A static version of `spin` drops `locals` to 1, moves `i` to slot 0, and sets `args_size` to 0. A Swing-based step debugger accompanying the post lets readers watch each instruction's effect on the frame.
The gap between the JVMS spec's illustrative code and `javac 21`'s output is a reminder that the spec describes semantics, not a compiler mandate; readers following the spec literally will mispredict real bytecode.
The `javac 21` layout (test-first, 5 instructions per iteration) is the opposite trade-off from the spec's (test-last, 4 per iteration): the spec optimizes for many iterations, while `javac` optimizes for simpler code generation at the cost of one extra instruction per round.
The `double` and `short` variants show that the JVM's instruction set is not type-uniform: missing instructions like `dinc` and `if_dcmplt` force longer instruction sequences, and `short` only exists through int truncation, making narrower types costlier than `int` itself.
An empty loop is the clearest proof that `javac` performs no semantic analysis of control flow; it translates source structure faithfully, delegating all optimization to the JIT, so bytecode payload size reflects source structure, not runtime cost.