So someone asked Is the ++ operator more efficient than a=a+1? a little while ago. I thought that I analyzed this before and initially said that there was no difference between a = a + 1
and the incremental operator ++
. As it turns out, a++
, ++a
and a += 1
all compile to the same bytecode, but a = a + 1
does not, as can be seen below:
public class SO_Test
{
public static void main(String[] args)
{
int a = 1;
a++;
a += 1;
++a;
}
}
Output:
Example:
public class SO_Test
{
public static void main(String[] args)
{
int a = 1;
a = a + 1;
a++;
a += 1;
++a;
}
}
Output:
In short, a = a + 1
issues iload_1
, iconst_1
, iadd
and istore_1
, whereas the others only use iinc
.
I've tried to rationalize this, but I am unable to. Is the compiler not smart enough to optimize the bytecode in this case? Is there a good reason that these are different? Is this handled by JIT? Unless I'm interpreting this incorrectly, it seems like I should never use a = a + 1
, which I thought for sure was just a stylistic choice.