nhouser9 nhouser9 - 2 months ago 7
Java Question

Performance of += in java

Background

Recently I posted an answer recommending something like:

x = x + 2;


Someone commented "Please use
x += 2;
instead."

Having studied assembly language and compilers to some degree, I always assumed that these two statements would be reduced to the same assembly instructions. Therefore, I also thought that there would be no performance difference between the two, and that the only difference was a matter of opinion and style.

After recieving the above comment, I was curious, and did a quick google and SO search, which returned nothing.

My Question

Is there any performance difference between
x = x + 2;
and
x += 2
in java? Or is the only difference in readability and style, making the choice between the two a matter of opinion?

Please provide evidence, not opinion.

Answer

Below is what my compiler does.

Java code:

public static void x( int x)
{
    x = x + 2;
}

Byte code:

public static void x(int);
  Code:
     0: iinc          0, 2
     3: return

Java code:

public static void x( int x)
{
    x += 2;
}

Byte code:

public static void x(int);
  Code:
     0: iinc          0, 2
     3: return

As you can see, they compile to the same byte code. Java compiler heavily optimizes your code, so do not try to optimize it for trivial things, especially at the expense of readability.