The Lazy evaluation reference article from the English Wikipedia on 24-Apr-2004
(provided by Fixed Reference: snapshots of Wikipedia from wikipedia.org)

Lazy evaluation

In computer programming, lazy evaluation is a concept that attempts to minimize the work the computer has to do. It has two related, yet different, meanings that could be described as delayed evaluation and minimal evaluation. Besides performance increase, the most imporant benefit of lazy evaluation is it allows to construct an infinite data structure.

The opposite of lazy evaluation is eager evaluation, also known as strict evaluation. This is the normal evaluation method in most programming languages.

Minimal evaluation

Minimal evaluation is when an expression is only evaluated until the point where its final value is known. This means that sometimes not all the parts of an expression are evaluated.

  int a = 0;
  if (a && myfunc(b)) {
     do_something();
  }

In this example using the C programming language, minimal evalution would mean that myfunc(b) is never called. This is because a evaluates to false, and false and q evaluates to false for any value of q.

When using minimal evaluation it is important to know the expression evaluation order. This is guaranteed in some programming languages (e. g. C: left to right; Java: left to right), but not in all.

Delayed evaluation

Delayed evaluation is used particularly in functional languages. When using delayed evaluation, an expression is not evaluated as soon as it gets bound to a variable, but when the evaluator is forced to produce the expression's value.

Some programming languages delay evaluation of expressions by default, and some others provide functionss to delay evaluation. In Haskell evaluation is delayed by default. In the Scheme programming language, evaluation can be delayed by saying (define delayed-expression (delay expression)). Then (force delayed-expression) will yield the value of expression.

Delayed evaluation has the added advantage of being able to create infinite lists without infinite loops or size matters in computation. One could create a function that creates an infinite list of Fibonacci numbers. The calculation of the n-th Fibonacci number would be merely the extraction of that element from the infinite list. The entire infinite list is never calculated, but only the values that influence a calculation.

Lazy evaluation as a design pattern

As well as the formal concept of lazy evaluation in programming languages, lazy evaluation is a design pattern often seen in general computer programming.

For example, in modern computer window managers, the painting of information to the screen is driven by "expose events" which drive the display code at the last possible moment. By doing this, they avoid the over-eager computation of unnecessary display content.

Another example of laziness in modern computer systems is copy-on-write page allocation.

See also:

Compare: