Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 877
nhouser9 Avatar asked Jun 04 '26 09:06

nhouser9


1 Answers

Below is what Eclipse compiler does (see the edit below).

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.

Edit: Turns out not all compilers compile these statements to the same byte code. However, the original point still stands. Do not try to optimize your Java code for trivial things, especially at the expense of readability; because JIT compiler heavily optimizes your code while compiling the byte code into native machine code, even if some Java compilers skip some optimizations.

like image 170
uoyilmaz Avatar answered Jun 06 '26 22:06

uoyilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!