Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the ++ operator more efficient than a=a+1? [closed]

Tags:

java

increment

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

like image 233
anakin Avatar asked Dec 03 '22 21:12

anakin


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: 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.

like image 122
Steve P. Avatar answered Dec 11 '22 10:12

Steve P.


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

like image 40
Paul Samsotha Avatar answered Dec 11 '22 12:12

Paul Samsotha