4

In Java, Is the increment operator more efficient that a simple addition operation?

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95

2 Answers2

14

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: enter image description here

Example:

public class SO_Test
{
    public static void main(String[] args)
    {
        int a = 1;
        a = a + 1;
        a++;
        a += 1;
        ++a;    
    }
}

Output: enter image description here

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.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
2

It's not more efficient, it's just cleaner looking code.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720