本文介绍了x = x + 1和x ++在实现上的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的教授最近说,尽管 x = x + 1 x ++ 显然会给出相同的结果,它们在JVM中的实现方式有所不同。这是什么意思?编译器不是这样的:嘿,我看到 x ++ ,所以我将其切换为 x = x + 1 并进行

My professor recently said that although x = x + 1 and x++ will obviously give the same result, there is a difference in how they are implemented in the JVM. What does it mean? Isn't compiler like: hey, I see x++ so I will switch it to x = x + 1 and carry on?

我怀疑在效率方面是否存在差异,但是如果组装在这些情况下会有所不同,我会感到惊讶...

I doubt there is any difference when it comes to efficiency, but I would be surprised if assembly would be different in those cases...

推荐答案

我想您的教授可能是在<$ c之后 x 的值$ c> x = x + 1 和 x ++ 相同。只是重新表达一下,因为它似乎在解释问题时造成混乱。

I guess your professor perhaps meant - the value of x after x = x + 1 and x++ will be same. Just to re-phrase, as it seems to be creating confusion in interpreting the question.

好吧,尽管 x 相同,它们是不同的运算符,并且在字节码中使用不同的JVM指令。 x + 1 使用指令,而 x ++ 使用指令。尽管这取决于编译器。编译器可以自由地对特定操作使用不同的指令集。我已经针对 javac 编译器进行了检查。

Well, although the value of x will be same, they are different operators, and use different JVM instructions in bytecode. x + 1 uses iadd instruction, whereas x++ uses iinc instruction. Although this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation. I've checked this against javac compiler.

对于 eclipse 编译器,从一个来自@Holger的以下评论:

For eclipse compiler, from one of the comment below from @Holger:

您可以使用 javap 命令。让我们考虑以下类:

You can check the byte code using javap command. Let's consider the following class:

class Demo {
    public static void main(String[] args) {
        int x = 5;

        x = x + 1;
        System.out.println(x);

        x++;
        System.out.println(x);
    }
}

编译以上源文件,并运行以下命令:

Compile the above source file, and run the following command:

javap -c Demo

代码将编译为以下字节码(仅显示 main 方法):

The code will be compiled to the following bytecode (just showing the main method):

 public static void main(java.lang.String[]);
   Code:
      0: iconst_5
      1: istore_1
      2: iload_1
      3: iconst_1
      4: iadd
      5: istore_1
      6: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
      9: iload_1
     10: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
     13: iinc          1, 1
     16: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
     19: iload_1
     20: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
     23: return

这篇关于x = x + 1和x ++在实现上的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:14