i++ vs ++i in Java: Which Is Faster in Loops? Bytecode Deep Dive
An interview question about choosing i++ or ++i in a for‑loop leads to a bytecode‑level analysis that reveals both forms compile to the same ++i instruction after JVM optimization, making their performance essentially identical in typical Java loops.
Earlier a friend was asked in an interview whether to use i++ or ++i in a for loop. The interviewer suggested considering execution efficiency.
In a for loop, should we use i++ or ++i?
We examine the two forms from a bytecode perspective. Both post‑increment
i++and pre‑increment
++iare not atomic operations, so we look at the generated bytecode.
Thought Process
We start with a simple method that assigns a value and performs
i++:
<code>public static void main(String[] args) {
int i = 3;
int j = i++;
System.out.println(j);
}
</code>Using
javapto decompile we obtain the following bytecode:
The key instructions involve loading the variable and the
iincoperation, which updates the local variable directly.
<code>2: iload_1
3: iinc 1, 1
</code>This translates roughly to:
<code>int temp = i;
i = i + 1;
</code>Next we replace
i++with
++iand repeat the analysis.
<code>public static void main(String[] args) {
int i = 3;
int j = ++i;
System.out.println(j);
}
</code>Decompiling yields:
The bytecode for
++iconsists of a single
iincinstruction:
<code>2: iinc 1, 1
</code>Thus
++iavoids the extra temporary variable introduced by
i++, giving a slight efficiency advantage when the result value is not used.
Increment in a for Loop
We compare two loops, one using
i++and the other
++i:
<code>// i++ post‑increment
public class ForIpp {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
// ++i pre‑increment
public class ForPpi {
public static void main(String[] args) {
for (int i = 0; i < 5; ++i) {
System.out.println(i);
}
}
}
</code>Decompiling both classes shows identical bytecode, both using the
iincinstruction for the loop increment.
This occurs because the Java compiler optimizes the loop increment to the pre‑increment form regardless of the source syntax.
Conclusion
In typical Java for‑loops, the JVM compiles both
i++and
++ito the same
iincbytecode instruction, making their runtime performance effectively identical.
Therefore, the two increment styles have the same efficiency in a for loop.
Note: The code was tested on Java 1.8.0_261‑b12.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.