++运算符比a = a + 1更有效吗? [英] Is the ++ operator more efficient than a=a+1?

查看:140
本文介绍了++运算符比a = a + 1更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,增量运算符是否比简单的加法运算更有效?

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

推荐答案

它编译为完全相同的字节代码。这都是首选问题。

编辑
事实证明这是 NOT true。

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;    
    }
}

输出:

示例:

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

输出:

可以在 Java字节码指令列表页面。简而言之, a = a + 1 发出 iload_1 iconst_1 iadd istore_1 ,而其他人只使用 iinc

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.

来自@NPE:


流行的理念是javac故意选择不是
优化生成的代码,依靠JIT编译器在
运行时执行此操作。后者有更好的关于执行
环境(硬件架构等)的信息,以及代码如何在运行时使用

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.

这篇关于++运算符比a = a + 1更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆