这两种情况不同

时间:2013-12-11 16:28:22

标签: java if-statement

我只是在想,以下方案之间是否有任何性能上的好处。

案例1

int x = 2;
boolean y = false;

if (x == 2) {
  y = true;
}

案例2

int x = 2;
boolean y = (x == 2);

我的想法是,案例1更具可读性。

3 个答案:

答案 0 :(得分:6)

性能上会有微小的微小差异(第一个版本会添加额外的if指令,但即使这样也可能被静态编译器或JIT编译器优化掉了,但无论如何它'可以忽略不计。对于这样一个简单的情况,最好优化可读性,忘记微优化。

答案 1 :(得分:4)

在这两种情况下你都是

  • x与文字2
  • 进行比较
  • y设置为值

但只有在第一种情况下才有分支。在第二种情况下,您只需将y设置为比较结果。

案例2因此而执行的操作较少。

但无论如何,编译器可能会以这种方式优化它。

答案 2 :(得分:3)

彼得开始了,但没有说完。供参考(Java 7编译器),这个

public class Test {
    public static void main(String[] args) {
        int x = 2;
        boolean y = (x == 2);
    }
}

编译到

  public static void main(java.lang.String[]);
    Code:
       0: iconst_2           // load the int value 2 onto the stack
       1: istore_1           // store int value into variable 1
       2: iload_1            // load an int value from local variable 1
       3: iconst_2           // load the int value 2 onto the stack
       4: if_icmpne     11   // if ints are not equal, branch to instruction at branchoffset 
       7: iconst_1           // load the int value 1 onto the stack (true)
       8: goto          12
      11: iconst_0           // load the int value 0 onto the stack (false)
      12: istore_2           // store int value into variable 2
      13: return 

public class Test {
    public static void main(String[] args) {
        int x = 2;
        boolean y = false;

        if (x == 2) {
          y = true;
        }
    }

}

编译到

 public static void main(java.lang.String[]);
    Code:
       0: iconst_2          // load the int value 2 onto the stack
       1: istore_1          // store int value into variable 1
       2: iconst_0          // load the int value 0 onto the stack (false)
       3: istore_2          // store int value into variable 2
       4: iload_1           // load an int value from local variable 1
       5: iconst_2          // load the int value 2 onto the stack
       6: if_icmpne     11  // if ints are not equal, branch to instruction at branchoffset
       9: iconst_1          // load the int value 1 onto the stack
      10: istore_2          // store int value into variable 2
      11: return    

两者都有分支声明。

要回答这个问题,你真的不会有任何收获。