What javac does
x++ and friends
iinc for locals; read, add and write for fields and arrays, with dup to keep the value.
x++ compiles very differently depending on what x is. An int local variable has its own instruction, iinc, which changes the variable in place without touching the stack. Fields and array elements need a read, an add and a write, plus dup instructions to keep the expression's value.
The source
// x++ in its many forms: iinc for locals, read-modify-write for fields and arrays.
public class Increments {
int field;
static long counter;
static int local(int i) {
i++;
int a = i++;
int b = ++i;
return a + b;
}
int field() {
return field++;
}
static long staticLong() {
return ++counter;
}
static void array(int[] a, int i) {
a[i]++;
}
static void big(int i) {
i += 1000;
System.out.println(i);
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- In
local(),i++,i++and++iare alliinc 0, 1. The only difference is whether theiloadthat reads the value comes before or after. return field++usesdup_x1to keep the old value underneath the object reference thatputfieldconsumes.return ++counteron a static long usesdup2to copy the new two-slot value.a[i]++usesdup2to keep the array and the index for the store.i += 1000does not fitiinc's one-byte constant, so it becomeswideiinc.
Increments.class
static int local(int i)
int field()
static long staticLong()
static void array(int[] a, int i)
static void big(int i)
javac --release 8 to 25 (the same bytecode for every release)