From Wikipedia:
Lazy evaluation is:
In programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed
Short-circuit evaluation is:
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation denotes the semantics of some Boolean operators in some programming languages in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression
So what's the difference between them for example when I have:
if(false && true && true) {
//boo
}
As far as I know, compiler doesn't execute expressions after false
because I have &&
so the whole expression will be false
finally. (right?)
So is that behavior called Lazy evaluation or Short-circuit evaluation?
Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.
Lazy evaluation is used in Unix map functions to improve their performance by loading only required pages from the disk. No memory will be allocated for the remaining pages.
Lazy evaluation (or call-by-need) delays evaluating an expression until it is actually needed; when it is evaluated, the result is saved so repeated evaluation is not needed. Lazy evaluation is a technique that can make some algorithms easier to express compactly or much more efficiently, or both.
AND(&&) short circuit:If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is returned.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With