In Java, Is the increment operator more efficient that a simple addition operation?
It compiles to the exact same byte code. It's all a matter of preference.
EDIT:
As it turns out this is NOT true.
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:
The differences can be analyzed on the Java bytecode instruction listings page. In short, a = a + 1
issues iload_1
, iconst_1
, iadd
and istore_1
, whereas the others only use iinc
.
From @NPE:
The prevailing philosophy is that javac deliberately chooses not to optimize generated code, relying on the JIT compiler to do that at runtime. The latter has far better information about the execution environment (hardware architecture etc) as well as how the code is being used at runtime.
So in conclusion, besides not compiling to the same byte code, with exceedingly high probability, it won't make a difference. It's just a stylistic choice.
It's not more efficient, it's just cleaner looking code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With