跪拜 Guibai
← Back to the summary

An empty for loop's bytecode: 8 instructions, 56 steps, and why javac won't delete it

In the output of javap -v, the Code of the spin method looks like this ⬇️

  void spin();
    descriptor: ()V
    flags: (0x0000)
    Code:
      stack=2, locals=2, args_size=1
         0: iconst_0
         1: istore_1
         2: iload_1
         3: bipush        10
         5: if_icmpge     14
         8: iinc          1, 1
        11: goto          2
        14: return

stack and locals are the two sizes from Section 2.6 "Frames". We already covered the relevant background in the previous post when exploring the bytecode instructions for the add method; in this post we use the spin method from Section 3.2 of the spec to see how an empty loop translates into jump instructions.

Example: spin in Spin.java

The example code for this post ⬇️ (save it as Spin.java)

public class Spin {
    public static void main(String[] args) {
        new Spin().spin();
    }

    void spin() {
        int i;
        for (i = 0; i < 10; i++) {
            ; // Loop body is empty
        }
    }
}

The example in Section 3.2 of the spec uses the loop condition i < 100 ⬇️

image.png

To avoid manually clicking the Step button over a hundred times during the GUI walkthrough, Spin.java changes the condition to i < 10; the compiled instruction structure is identical.

Run these two commands to compile Spin.java and inspect the resulting class file details (I'm using JDK 21):

javac -g Spin.java # -g generates debug info like LocalVariableTable
javap -v Spin

javap -v outputs additional information, including the constant pool and more; only the part related to spin() is excerpted here.

  void spin();
    descriptor: ()V
    flags: (0x0000)
    Code:
      stack=2, locals=2, args_size=1
         0: iconst_0
         1: istore_1
         2: iload_1
         3: bipush        10
         5: if_icmpge     14
         8: iinc          1, 1
        11: goto          2
        14: return
      LineNumberTable:
        line 8: 0
        line 11: 14
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      15     0  this   LSpin;
            2      13     1     i   I
      StackMapTable: number_of_entries = 2
        frame_type = 252 /* append */
          offset_delta = 2
          locals = [ int ]
        frame_type = 11 /* same */

locals=2: slot 0 is this, slot 1 is i. stack=2: the operand stack never holds more than two values at once anywhere in this method. The two entries in LineNumberTable correspond to source line 8 (the loop) and line 11 (the closing } of the method). StackMapTable holds frame information used for bytecode type-checking; it's not central to this post, so we won't expand on it.

Its frame structure ⬇️

image.png

The left shows the two slots for locals=2, numbered slot 0 and slot 1 below the cells; the right shows the two slots for stack=2, numbered on the right side, with slot 0 at the bottom. The method has just been invoked; i hasn't been assigned yet (shown as —), and the operand stack is empty.

The screenshots below come from the companion SpinDemo.java: a Swing window that steps through these 8 instructions one at a time, 56 steps total for this example (the title bar reads step 0 / 56). Download and run it (requires JDK 16+; this post uses JDK 21): ⬇️

javac SpinDemo.java
java SpinDemo

The toolbar at the top adjusts speed; Step ▶ executes one step, Run autoplays the remaining instructions, Reset returns to the initial state ⬇️

image.png

The image above is the full runtime window: the toolbar handles speed and execution control, the left pane shows source and bytecode, and the right frame panel (local variables + operand stack) is what appears in the step screenshots later.

Blue marks values written or pushed by the current step; an amber border marks the slot read by the current step.

Instruction notation: offsets double as jump targets

Section 3.1 defines the format for this chapter's examples ⬇️

Each instruction takes the form:

<index> <opcode> [ <operand1> [ <operand2>... ]] [<comment>]

index is the position of the instruction in the method's bytecode array, i.e. the byte offset from the start of the method. It can serve as a jump target; for example, goto 2 jumps to the iload_1 at index 2. Control-transfer instructions actually take a relative offset as their operand; javap converts it to the target index for display, so the numbers in the listing can be read directly.

Offsets aren't contiguous: iload_1, istore_1 etc. are 1 byte; bipush with its one-byte immediate operand totals 2 bytes; if_icmpge, iinc, and goto are 3 bytes each; return is 1 byte, filling 0~14 exactly.

Not quite the same as the spec's listing

Section 3.2 says the compiler "may translate" it as ⬇️

0 iconst_0      // Push int constant 0
1 istore_1      // Store into local variable 1 (i=0)
2 goto 8        // First time through don't increment
5 iinc 1 1      // Increment local variable 1 by 1 (i++)
8 iload_1       // Push local variable 1 (i)
9 bipush 100    // Push int constant 100
11 if_icmplt 5  // Compare and loop if less than (i < 100)
14 return       // Return void when done

javac 21 chooses another equivalent arrangement: check first, then increment. Both use nearly the same instructions; only the conditional branch is inverted to if_icmpge. The rest differ in instruction ordering and jump direction ⬇️

Spec example javac 21
First entry into loop goto 8, skipping the increment goes straight to iload_1 check
Conditional branch if_icmplt 5, jump back when less if_icmpge 14, exit when greater-or-equal
Increment position before the condition check after the condition check
Jump back none; only the goto 8 on first entry goto 2, back to the check at each iteration's end
Instructions per iteration 4: if_icmplt jumps back itself 5: one extra goto

The executed operation sequence is identical: one initialization; each iteration checks whether i is below the upper bound, increments and returns to the check if so, otherwise returns. The screenshots and descriptions that follow use my local javac's actual output.

Stack machine: going instruction by instruction

Section 3.2 describes the execution model as ⬇️

The Java Virtual Machine is stack-oriented, with most operations taking one or more operands from the operand stack of the Java Virtual Machine's current frame or pushing results back onto the operand stack.

Apart from a few instructions that operate directly on local variables, most instructions go through the operand stack. Here is the state after each instruction of spin ⬇️

Instruction Stack (bottom to top) Slots used
0: iconst_0 [0] 1
1: istore_1 [] 0
2: iload_1 [i] 1
3: bipush 10 [i, 10] 2
5: if_icmpge 14 [] 0
8: iinc 1 1 [] 0
11: goto 2 [] 0
14: return [] 0

The peak number of slots on the stack is 2, reached after bipush: i and the upper bound are on the stack at the same time, exactly matching stack=2 ⬇️

spin-bipush.png

The i from the previous iteration is first pushed by iload_1, then bipush 10 pushes the upper bound, occupying 2 slots. if_icmpge then pops both values to compare, clearing the stack ⬇️

spin-if.png

This step's condition doesn't hold (0 >= 10 is false), so no jump happens and execution continues at instruction 8. The slot holding the i being read is painted amber; the stack is already empty.

Grouping these instructions by their effect on the stack, the pattern is simple:

Pushes and pops are counted in slots: int, float, and reference take 1; long and double take 2. spin only has int, so the additions and subtractions above are exactly slot counts; in the double variant below, a single dload_1 contributes 2.

Instructions later in this post can be sanity-checked for stack depth with this method.

Constants 0 and 10: why not the same instruction

Section 3.2 points out that the two constants in spin use two different push instructions ⬇️

The 0 is pushed using an iconst_0 instruction, one of the family of iconst_<i> instructions. The 100 is pushed using a bipush instruction, which fetches the value it pushes as an immediate operand.

The 100 in the quote is from the spec's original example; this post changes the bound to 10.

The iconst_<i> family covers int constants -1 through 5; the value is implicit in the opcode itself, needing no extra operand bytes. bipush carries a one-byte immediate.

So 0 uses iconst_0, one instruction, one byte; 10 isn't in -1~5, so it uses bipush 10, two bytes. Writing bipush 0 for 0 would also work; it would just cost the whole sequence one extra byte.

Why i lives in slot 1

Section 3.2 explains ⬇️

The int i in spin is stored as Java Virtual Machine local variable 1. Because most Java Virtual Machine instructions operate on values popped from the operand stack rather than directly on local variables, instructions that transfer values between local variables and the operand stack are common...

An instance method's slot 0 holds this, so i starts at slot 1. The _1 in istore_1 and iload_1 is the slot number, no separate operand needed. In the LocalVariableTable, i has Start=2: its scope begins after the first assignment and ends at the method's close.

iinc: increment without touching the operand stack

Section 3.2 says about iinc ⬇️

The iinc instruction increments the contents of a local variable by a one-byte signed value. The iinc instruction in spin increments the first local variable (its first operand) by 1 (its second operand).

The two operands of iinc 1 1 are the slot number and the increment: add 1 to the i in slot 1, writing straight back into the local variable table, never touching the operand stack. "the first local variable" in the quote means the local variable at index 1, not slot 0 — slot 0 is this ⬇️

spin-iinc.png

That's the key difference from iadd: iadd takes two values off the stack and pushes the result back; iinc needs no push or pop, so this step still has 0 slots on the stack (written as depth = 0 / 2 in the figure). The increment is a one-byte signed value in the range -128~127.

Four or five instructions per iteration

Section 3.2 reduces the spin loop to four instructions ⬇️

5 iinc 1 1      // Increment local variable 1 by 1 (i++)
8 iload_1       // Push local variable 1 (i)
9 bipush 100    // Push int constant 100
11 if_icmplt 5  // Compare and loop if less than (i < 100)

With javac 21's offsets, one iteration is five instructions ⬇️

  1. 2: iload_1: pushes i
  2. 3: bipush 10: pushes the upper bound
  3. 5: if_icmpge 14: pops both values, compares; jumps to 14 if i >= 10
  4. 8: iinc 1 1: when not exiting, i plus 1
  5. 11: goto 2: back to the check, starting the next iteration

The five instructions chain end to end into exactly one loop ⬇️

image.png

The diamond labeled i >= 10 ? in the figure is if_icmpge: true goes straight to return; false passes through iinc and goto 2 back to the loop head. The goto 2 back edge is the extra instruction javac 21 adds over the spec's example. The hexagon at the bottom labeled goto 2 is PlantUML's closing marker for a repeat loop, not another decision; executing goto 2 unconditionally jumps back to instruction 2. The spec version is flipped: the test sits at the bottom of the loop, and goto 8 walks to the test on first entry. That's where the first two rows of the comparison table above come from. The PlantUML source for this figure is in flow.puml.

The spec version runs 4 instructions per iteration; javac 21 runs 5, and the extra one is goto: the spec places the test at the loop end, so if_icmplt 5 completes the backward jump itself. javac 21 tests first, so the backward jump needs its own instruction. Section 3.5 lays out the trade-off clearly: put the test at the end and each iteration saves one instruction, at the cost of one extra goto to reach the test on first entry (wasted when the loop body never runs); loops typically run many iterations, so what's saved outweighs what's spent. The 5 steps per iteration in the 56 steps mentioned earlier include this goto.

goto 2 hands control back to iload_1; the stack is empty at that point, so the next iteration starts from a clean state ⬇️

spin-goto.png

The boundary is easy to hand-trace: at i = 9, 9 >= 10 doesn't hold, so it increments to 10 and returns to the test; 10 >= 10 holds, so it jumps to 14 and returns. The loop body runs 10 times; the condition test runs 11 times.

Extension: what happens with double and short

Section 3.2 gives two variants after spin, changing only the loop variable's type. First the double version ⬇️

void dspin() {
    double i;
    for (i = 0.0; i < 100.0; i++) {
        ; // Loop body is empty
    }
}

The spec's instructions are ⬇️

0 dconst_0      // Push double constant 0.0
1 dstore_1      // Store into local variables 1 and 2
2 goto 9        // First time through don't increment
5 dload_1       // Push local variables 1 and 2
6 dconst_1      // Push double constant 1.0
7 dadd          // Add; there is no dinc instruction
8 dstore_1      // Store result in local variables 1 and 2
9 dload_1       // Push local variables 1 and 2
10 ldc2_w #4    // Push double constant 100.0
13 dcmpg        // There is no if_dcmplt instruction
14 iflt 5       // Compare and loop if less than (i < 100.0)
17 return       // Return void when done

Three things worth noting:

  1. i occupies slot 1 and slot 2; dstore_1 writes two slots at once, but the value is accessed only through the smaller index 1
  2. There's no dinc instruction; i++ needs dload_1, dconst_1, dadd, dstore_1 four instructions — dadd has to push i onto the stack first to have two operands. What the int version does in one iinc costs three extra instructions here
  3. There's no if_dcmplt; comparisons first use dcmpg to push -1, 0, or 1, then iflt tests it

Compiling with my local javac 21, the test is likewise placed first ⬇️

  void dspin();
    descriptor: ()V
    flags: (0x0000)
    Code:
      stack=4, locals=3, args_size=1
         0: dconst_0
         1: dstore_1
         2: dload_1
         3: ldc2_w        #7                  // double 100.0d
         6: dcmpg
         7: ifge          17
        10: dload_1
        11: dconst_1
        12: dadd
        13: dstore_1
        14: goto          2
        17: return

The skeleton matches spin: test first, then increment. dcmpg pushes the comparison result -1/0/1 onto the stack, and ifge exits the loop when it's not less than 0. locals=3 is this plus i taking two slots; stack=4 is the peak after dload_1 and ldc2_w place both doubles on the stack, each taking 2 slots. The stack becoming 4 when b was changed to long at the end of the previous post was the same reason.

Now the short version ⬇️

void sspin() {
    short i;
    for (i = 0; i < 100; i++) {
        ; // Loop body is empty
    }
}

short has no dedicated load, store, or addition instructions; sspin can only promote i to int, compute, then truncate back to short. The spec's instructions are ⬇️

0 iconst_0
1 istore_1
2 goto 10
5 iload_1       // The short is treated as though an int
6 iconst_1
7 iadd
8 i2s           // Truncate int to short
9 istore_1
10 iload_1
11 bipush 100
13 if_icmplt 5
16 return

Just as dspin has no dinc, sspin can't use iinc either: it does addition without the i2s truncation.

Compiling with my local javac 21, sspin also tests first ⬇️

  void sspin();
    descriptor: ()V
    flags: (0x0000)
    Code:
      stack=2, locals=2, args_size=1
         0: iconst_0
         1: istore_1
         2: iload_1
         3: bipush        100
         5: if_icmpge     16
         8: iload_1
         9: iconst_1
        10: iadd
        11: i2s
        12: istore_1
        13: goto          2
        16: return

The skeleton is identical to spin (with if_icmplt inverted to if_icmpge); only the data-movement and arithmetic instructions change: the single iinc 1 1 for the increment becomes five instructions: iload_1 + iconst_1 + iadd + i2s + istore_1.

The GUI in this post demonstrates only the int version of spin; the frame-by-frame state of dspin and sspin is deferred until type support is covered later.

After return

return is the last instruction; once it executes, the frame pops and the local variable table and operand stack cease to exist ⬇️

spin-return.png

By now i is 10; return hands void back to the caller, and the green tooltip reads return: spin() finished with i = 10; the frame in the figure has popped, drawn as a gray dashed outline. The whole execution totals 2 + 10 × 5 + 4 = 56 steps: 2 for initialization; 5 instructions per iteration over 10 iterations, 50 steps; the final test plus return is 4 steps.

Numbers at a glance

Number Meaning In spin
locals=2 number of slots in the local variable table this 1 + i 1
stack=2 maximum operand stack depth i and the upper bound on the stack after bipush 10
args_size=1 argument count (not slot count) this counts as an argument; spin declares no explicit parameters

args_size=1 and locals=2 mean different things: spin declares no parameters, but instance methods count this as one argument; i is a local variable inside the method, occupying a slot but not counted as an argument.

Here's an exercise: add static to spin and run javap again. How do locals, args_size, and i's slot number change?

Below is the reference answer; try it yourself before reading on.

this no longer occupies slot 0: locals becomes 1, i moves to slot 0, args_size becomes 0, and the instructions touching i change to istore_0, iload_0, iinc 0 1 ⬇️

  static void spin();
    descriptor: ()V
    flags: (0x0008) ACC_STATIC
    Code:
      stack=2, locals=1, args_size=0
         0: iconst_0
         1: istore_0
         2: iload_0
         3: bipush        10
         5: if_icmpge     14
         8: iinc          0, 1
        11: goto          2
        14: return

The new Spin().spin() call in main still compiles unchanged: javac still news the instance, pops it away, then calls the static method with invokestatic. Calling a static method through an instance is poor style though; with -Xlint:static javac warns to qualify it with the type name, and Spin.spin() is cleaner.

Comparison with add

add(int, int) spin()
Control flow none; four instructions run sequentially if_icmpge exits, goto loops back
Local variable table this, a, b this, i
locals / stack 3 / 2 2 / 2
Instructions that skip the operand stack none iinc
Peak slot count on stack 2 2

Taken together with the previous post, the frame's two sizes line up: locals is the slot count, stack is the operand stack's maximum depth during instruction execution.

Summary

  1. In Section 3.1, index is a byte offset and doubles as a jump target; instruction lengths vary, so offsets aren't contiguous.
  2. spin consists of initialization, condition test, increment, and backward jump. The spec puts the test at the end, using goto 8 + if_icmplt 5, 4 instructions per iteration; javac 21 tests first, using if_icmpge 14 + goto 2, 5 instructions per iteration. Both are equivalent.
  3. Constant pushes: -1 through 5 use iconst_<i>, value implicit in the opcode; 10 uses bipush with a one-byte immediate.
  4. i sits in slot 1 because slot 0 is this.
  5. iinc modifies a local variable directly, skipping the operand stack.
  6. With double as the loop variable: i takes two slots, there's no dinc, i++ needs four instructions; there's no if_dcmplt, comparisons need dcmpg plus iflt two instructions. With short: it can only be promoted to int for arithmetic, then truncated by i2s.
  7. spin has locals=2, stack=2; the peak slot count on the stack occurs after bipush.

One last question: this loop does nothing, so why doesn't javac optimize it away? Because javac doesn't do loop elimination at that level: it never reasons that "this loop has no effect on the program's result"; it only translates the source faithfully into instructions. The listing above is the evidence: the loop is still there. The JIT compiler at runtime is the one that may recognize an empty loop and eliminate it, a topic for when the execution engine is covered later.

The next post looks at Section 3.3's arithmetic instructions: why int and long addition use different bytecodes, and how many slots each occupies on the operand stack.

References