Delay execution is almost always a boon. But then there are cases when it’s a problem and you resort to “fetch” (in Nhibernate) to eager fetch it.
Do you know practical situations when lazy evaluation can bite you back…?
Lazy evaluation's is not always better. The performance benefits of lazy evaluation can be great, but it is not hard to avoid most unnecessary evaluation in eager environments- surely lazy makes it easy and complete, but rarely is unnecessary evaluation in code a major problem.
"Lazy" evaluation is performing operations when and as they are needed. It is useful when it is a feature of a programming language or library because it is generally harder to implement lazy evaluation on your own than simply to precalculate everything up front.
In non-strict evaluation, arguments to a function are not evaluated unless they are actually used in the evaluation of the function body. Under Church encoding, lazy evaluation of operators maps to non-strict evaluation of functions; for this reason, non-strict evaluation is often referred to as "lazy".
Lazy evaluations are one of the Functional Programming techniques for implementing the efficient code. So, almost every Functional Programming language supports the lazy evaluation.
You cannot do a reduction (eg. a fold) on input data in constant space with lazy evaluation, as the delayed evaluation of each reduction step results in linear space complexity. You must instead force-evaluate the result of each reduction step to keep the space usage constant.
For example, hashing a file in Haskell. You might be well meaning and read the input file lazily chunk-by-chunk, adding each chunk to the digest, but behind your back Haskell is actually making a thunk for every chunk you add to the digest, leaving the entire file in memory in these thunks until the resulting digest is actually evaluated. Ouch!
See last comment here: Haskell lazy I/O and closing files
Lazy evaluation is not useful in situations where performance is critical and a value must always be evaluated. In these cases you are better off just evaluating the value and being done with it, because the overhead of lazy evaluation will be wasted.
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