In Java, Is the increment operator more efficient that a simple addition operation?
-
2Could you provide a source for that? – Jeroen Vannevel Nov 13 '13 at 14:42
-
Post- or pre-incremental? The question should be rather starting with **Is** than with *Why* – Eel Lee Nov 13 '13 at 14:43
-
More efficient? Which benchmark standard do you present to back that claim? – Hanky Panky Nov 13 '13 at 14:44
-
When will this ever be the bottleneck for any real program? – Zong Nov 13 '13 at 16:03
2 Answers
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.

- 14,489
- 8
- 42
- 72
-
This is the answer needed. A small sample that displays the byte code generation so there's actually something to prove, and we're all done here. – Jeroen Vannevel Nov 13 '13 at 14:47
-
-
And while you're at it, you should include `a += 1` which is slightly different under some circumstances. – Petr Janeček Nov 13 '13 at 14:50
-
-
Since +1 has some extra instructions, does it mean on the very micro level ++ is fast than +1? – inquisitive Aug 12 '15 at 05:58