我知道 Java 在这种情况下有智能/惰性评估:
public boolean isTrue() {
boolean a = false;
boolean b = true;
return b || (a && b); // (a && b) is not evaluated since b is true
}
但是关于:
public boolean isTrue() {
boolean a = isATrue();
boolean b = isBTrue();
return b || a;
}
Is isATrue()
打电话即使isBTrue()
返回真?
好吧,就语言而言 - 是的,这两个函数都被调用了。
如果您将函数重写为:
public boolean isTrue() {
return isBTrue() || isATrue();
}
如果第一个函数为 true,那么第二个函数将不会被调用。
但这是短路评估, not 惰性评估。惰性评估案例看起来像这样:
public interface LazyBoolean {
boolean eval();
}
class CostlyComparison implements LazyBoolean {
private int a, b;
public CostlyComparison(int a, int b) {
this.a=a;
this.b=b;
}
@Override
public boolean eval() {
//lots of probably not-always-necessary computation here
return a > b;
}
}
public LazyBoolean isATrue() {
return new CostlyComparison(10,30); //just an example
}
public boolean isTrue() { // so now we only pay for creation of 2 objects
LazyBoolean a = isATrue(); // but the computation is not performed;
LazyBoolean b = isBTrue(); // instead, it's encapsulated in a LazyBoolean
return b.eval() || a.eval(); // and will be evaluated on demand;
// this is the definition of lazy eval.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)