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

Deadly 提交于 2019-12-22 08:19:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!