Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is lazy evaluation not useful?

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…?

like image 441
Cherian Avatar asked Aug 30 '09 17:08

Cherian


People also ask

Is lazy evaluation always better?

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.

When should I use lazy evaluation?

"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.

Is lazy evaluation strict or non strict?

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".

Do all functional programming languages use lazy evaluation?

Lazy evaluations are one of the Functional Programming techniques for implementing the efficient code. So, almost every Functional Programming language supports the lazy evaluation.


2 Answers

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

like image 116
Jesse Avatar answered Sep 20 '22 18:09

Jesse


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.

like image 29
vy32 Avatar answered Sep 18 '22 18:09

vy32