我有以下声明:
isEnabled = false;
if(foo(arg) && isEnabled) {
....
}
public boolean foo(arg) {
some really long running code
}
交换if中的语句是否有意义?
if(isEnabled && foo(arg)) { ... }
还是编译器为我做了优化?
发布于 2015-05-28 11:12:13
注意,如果foo()
也有side effects,那么这两个表达式不具有相同的行为。
如果它正在操作程序的状态,那么如果您总是调用它,或者只作为isEnabled
值的依赖项调用它,则会产生很大的不同。
例如,考虑:
boolean foo(Object arg) {
someLocalVariable = arg;
//do some calculation and return an answer
}
如果总是调用foo()
,或者只在打开isEnabled
的情况下调用它,会导致以下两个表达式完全不同:
if (isEnabled && foo(arg)) { ...} //local variable changes only if isEnabled==true
if (foo(arg) && isEnabled) { ...} //local variable always changes
发布于 2015-05-28 11:09:44
在这种情况下,编译器不会进行任何优化。
if(isEnabled && foo(arg)) { ... }
总是更好的方法。
因为我猜您知道,当isEnabled
为false时,它不会计算foo(arg)
。编译器将维护您的指令序列。
发布于 2015-05-28 11:11:38
由于编译器必须保持其本身的逻辑(这包括语句的顺序),所以不会对其进行优化。
假设foo()
有一个副作用,这是代码的其他部分所依赖的,更改顺序可能会破坏这一点。当然,在大多数情况下,这不是很好的样式,但是编译器不能依赖或执行样式,所以它必须信任这里的开发人员。
示例:
int x = 0;
boolean foo(int arg) {
x = arg;
return x > 0;
}
void someMethod(int arg) {
boolean isEnabled = false;
if(foo(arg) && isEnabled) {
//whatever
}
//here you use x, I'll simply print it
System.out.println("x=" + x);
}
void someOtherMethod(int arg) {
boolean isEnabled = false;
if(isEnabled && foo(arg)) {
//whatever
}
//here you use x, I'll simply print it
System.out.println("x=" + x);
}
现在调用这些方法:
someOtherMethod(7); //foo(7) will not be called so x will still be 0
someMethod(5);
你会得到输出
x=0
x=5
https://stackoverflow.com/questions/30504850
复制相似问题