Lazy evaluation
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 (non-strict evaluation) and which also avoids repeated evaluations (sharing).
Description
The sharing can reduce the running time of certain functions by an exponential factor over other non-strict evaluation strategies, such as call-by-name.
The benefits of lazy evaluation include:
- The ability to define control flow (structures) as abstractions instead of primitives.
- The ability to define potentially infinite data structures. This allows for more straightforward implementation of some algorithms.
- Performance increases by avoiding needless calculations, and error conditions in evaluating compound expressions.
Lazy evaluation is often combined with memoization, as described in Jon Bentley's Writing Efficient Programs.
After a function's value is computed for that parameter or set of parameters, the result is stored in a lookup table that is indexed by the values of those parameters; the next time the function is called, the table is consulted to determine whether the result for that combination of parameter values is already available. If so, the stored result is simply returned. If not, the function is evaluated and another entry is added to the lookup table for reuse.
Lazy evaluation can lead to reduction in memory footprint, since values are created when needed. However, lazy evaluation is difficult to combine with imperative features such as exception handling and input/output, because the order of operations becomes indeterminate. Lazy evaluation can introduce space leaks.
The opposite of lazy evaluation is eager evaluation, sometimes known as strict evaluation. Eager evaluation is the evaluation strategy employed in most programming languages.
See also
- Combinatory logic
- Control flow
- Currying
- Dataflow
- Eager evaluation
- Evaluation strategy
- Expression (computer science)
- Functional programming
- Futures and promises
- Generator (computer programming)
- Graph reduction
- Incremental computing – a related concept whereby computations are only repeated if their inputs change. May be combined with lazy evaluation.
- Lambda calculus
- Lazy initialization
- Look-ahead
- Non-strict programming language
- Normal order evaluation
- Short-circuit evaluation (minimal)
External links
- Lazy evaluation @ Wikipedia.org