In programming language theory, lazy evaluation is an evaluation strategy that delays the evaluation of an expression until its value is needed and avoids repeated evaluations. Evaluation is the process of getting the root meaning of a piece of code. Many programming languages evaluate expressions immediately, but it can become inefficient as not all expressions are worth evaluating. The opposite of lazy evaluation is strict evaluation, in which an expression is evaluated immediately.
Lazy evaluation is used in combination with memoization, which is an optimization technique used to speed up computer programs by storing results of function calls and returning the cached results when the same inputs occur again. After a function’s value is computed for the parameter, the result is stored in a table that is indexed by the values of the parameter. The next time the function is called, the table is used to determine whether the result of that combination of parameter values is available. If it is, the stored result is returned. If not, the function is evaluated and another entry is added to the table for reuse.
Haskell is a programming language that has fundamentals based on lazy evaluation.
Benefits of lazy evaluation include:
While lazy evaluation is beneficial, it does have its drawbacks. It can be difficult to combine with essential features such as exception handling and input/output because the order of operations becomes indeterminate. Lazy evaluation can also introduce memory leaks.