问题描述
来自维基百科:
惰性评估 是:
Lazy evaluation is:
短路评估 是:
Short-circuit evaluation is:
例如,当我有时,它们之间有什么区别?
So what's the difference between them for example when I have:
if(false && true && true) {
//boo
}
据我所知,编译器不会在false
之后执行表达式,因为我有&&
,所以整个表达式最终将是false
. (对吗?)
As far as I know, compiler doesn't execute expressions after false
because I have &&
so the whole expression will be false
finally. (right?)
该行为是否称为惰性评估或短路评估?
推荐答案
区别在于,在懒惰求值的情况下,仅在需要时才对表达式进行求值,而在短路求值的情况下,表达式求值会在您之后立即停止知道结果.这是一种正交的概念.
The difference is that in case of lazy evaluation an expression is evaluated only when it is needed, while in case of short-circuit evaluation expression evaluation stops right after you know the result. It's sort of orthogonal notions.
惰性评估可以应用于任何计算(短路方案通常仅用于布尔型). 它不会切断无用的计算,但会延迟整个计算,直到需要结果为止.
Lazy evaluation can be applied to any computation (short-circuit scheme usually is used only with bools). It doesn't cut-off useless computation, but delays the whole computation until its result is required.
variable = bigAndSlowFunc() or evenSlowerFnc()
if (carry out heavy computations)
print "Here it is: ", variable
else
print "As you wish :-)"
如果评估是惰性的,则仅当我们选择进入if
的第一个(then
)分支时,才会计算variable
,否则不会计算.在评估阶段(当我们为print
准备参数时),短路方案可用于确定是否需要调用evenSlowerFnc
.
If evaluation is lazy, variable
will be computed only if we choose to go into the first (then
) branch of if
, otherwise it won't. At the evaluation stage (when we prepare arguments for print
) short-circuit scheme can be used to decide if we need to call evenSlowerFnc
.
因此在您的示例中,这是短路评估,因为没有发生计算延迟.
So in your example, it's short-circuit evaluation since no delay of computation happen.
这篇关于惰性评估和短路评估之间有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!