问题
In Java, Is the increment operator more efficient that a simple addition operation?
回答1:
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.
回答2:
It's not more efficient, it's just cleaner looking code.
来源:https://stackoverflow.com/questions/19956636/is-the-operator-more-efficient-than-a-a1