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 ++i are 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++:
public static void main(String[] args) {
int i = 3;
int j = i++;
System.out.println(j);
}Using javap to decompile we obtain the following bytecode:
The key instructions involve loading the variable and the iinc operation, which updates the local variable directly.
2: iload_1
3: iinc 1, 1This translates roughly to:
int temp = i;
i = i + 1;Next we replace i++ with ++i and repeat the analysis.
public static void main(String[] args) {
int i = 3;
int j = ++i;
System.out.println(j);
}Decompiling yields:
The bytecode for ++i consists of a single iinc instruction:
2: iinc 1, 1Thus ++i avoids 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:
// 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);
}
}
}Decompiling both classes shows identical bytecode, both using the iinc instruction 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 ++i to the same iinc bytecode 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
