Notes on lazy evaluation

By Andres Jaimes

- 2 minutes read - 273 words

Lazy evaluation is a strategy that delays expression evaluation until their value is needed. It also avoids repeated evaluations by returning previously computed results by storing them in a lookup table.

Why isn’t lazy evaluation used everywhere?

Lazy evaluations are not used everywhere (not used in every software currently produced) because of the following reasons:

  • Lazy evaluation requires book-keeping overhead - you have to know if it’s been evaluated yet and such things. Eager evaluation is always evaluated, so you don’t have to know. This is especially true in concurrent contexts.
  • Secondly, it’s trivial to convert eager evaluation into lazy evaluation by packaging it into a function object to be called later, if you so wish.
  • Thirdly, lazy evaluation implies a loss of control. What if I lazily evaluated reading a file from a disk? Or getting the time? That’s not acceptable.

We observe from the examples on the third bullet that lazy evaluation and side effects do not play well together. For example, a file could be modified by an external process and we might need to read the latest update.

Lazy evaluation is often combined with memoization (an optimization technique used to speed programs by storing the results of expensive function calls and returning the cached result when the same input occurs again.) Results are stored in a lookup table indexed by the values of the provided parameters. If a new parameter (or set of parameters) are provided, then a new entry is added to the table.

References