Java Performance – Difference Between `int a=a+1` and `a++`

javaperformancepost-increment

Is there any performance difference between using int a=a+1 and a++ in Java?

If so which is better and why? Could you briefly explain me to understand this?

Best Answer

First of all, the Java Language Specification doesn't say anything about timing. But assuming we're using a typical compiler such as Suns javac we see that all of the above examples (a++, ++a, a += 1, a = a + 1) could either be compiled into something like:

  • iinc instruction, working on variables:

    iload_<variable>
    iinc <variable>, 1
    istore_<variable>
    
  • iadd instuction, using the stack (here using variable 1 as a the storage):

    iload_1
    iconst_1
    iadd
    istore_1
    

It's up to the compiler to choose the best possible way to compile them. E.g. there is no difference between them. And it shouldn't be any difference between the statements - they all express the same thing - adding one to a number.

That beeing said, both the iinc and the iadd version can be compiled using the JIT to something fast and platform dependent, and in the end I would assume that a normal runtime compiles both versions into the same assembler code.


With my compiler, *jdk1.6.0_20* the "increment" methods even uses the same instruction.

public class Test {
    public static void main(String[] args) {

        int a = 0;

        a = a + 1;
        a += 1;
        a++;
        ++a;
    }
}

This is the disassembly:

Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iinc    1, 1   // a = a + 1;
   5:   iinc    1, 1   // a += 1;
   8:   iinc    1, 1   // a++;
   11:  iinc    1, 1   // ++a;
   14:  return

}