Java 这两种情况不同
我只是在想,以下场景之间是否存在性能方面的好处 案例1Java 这两种情况不同,java,if-statement,Java,If Statement,我只是在想,以下场景之间是否存在性能方面的好处 案例1 int x = 2; boolean y = false; if (x == 2) { y = true; } 案例2 int x = 2; boolean y = (x == 2); 我的想法是,案例1更具可读性 在这两种情况下,您都是 将x与文本2 将y设置为一个值 但只有在第一种情况下,你才有分支机构。在第二种情况下,您只需将y设置为比较结果 因此,案例2的操作更少 但无论如何,编译器可能会以这种方式为您进行优化 在性能
int x = 2;
boolean y = false;
if (x == 2) {
y = true;
}
案例2
int x = 2;
boolean y = (x == 2);
我的想法是,案例1更具可读性 在这两种情况下,您都是
- 将
与文本x
2
- 将
设置为一个值y
y
设置为比较结果
因此,案例2的操作更少
但无论如何,编译器可能会以这种方式为您进行优化 在性能上会有微小的差别(毕竟,第一个版本添加了一条额外的
if
指令,但即使这样也可能会被静态编译器或JIT编译器优化掉),但无论如何,它都可以忽略不计。对于这样一个简单的例子,最好是针对可读性进行优化,而不要考虑微观优化。Peter开始了,但没有完成。作为参考(Java7编译器),此
编译成
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
两者都有分支语句
要回答这个问题,你真的什么也得不到。你可以很容易地用时间戳测试它。JIT编译器可能会优化它,因为
x
是固定的。@SotiriosDelimanolis我只想知道这两者有什么不同。我不希望在这里有任何性能提升。看看字节码。有非常小的区别。
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