Programming Search⌘K

Conceptcore

Lazy evaluation

Also called lazy evaluation, laziness, call by need, non-strict evaluation, deferred execution, lazy initialization, delayed evaluation.

Lazy evaluation computes a value only when a program needs it, and usually stores the result for later use. It allows infinite sequences and avoids work whose result is never used.

Applies to
core-languages

Idea

Most languages evaluate an expression when the program reaches it. Lazy evaluation waits until the program needs the value. A lazy value is a description of a computation, often called a thunk, and the computation runs only when some code asks for the result. If no code asks, it never runs. If the result is stored after the first run, later requests get the stored value. Laziness lets a program describe a large or infinite sequence and use only the part that it needs:

def numbers():
    n = 0
    while True:
        print("computing", n)
        yield n
        n += 1


evens = (n for n in numbers() if n % 2 == 0)
print("nothing computed yet")
print(next(evens))
print(next(evens))
Output
nothing computed yet
computing 0
0
computing 1
computing 2
2

The generator describes all natural numbers, but it computes a number only when next asks for one. Haskell uses lazy evaluation for every expression. Most other languages are eager by default and give laziness through generators, iterators, streams and lazy values.

How it works

Non-strict evaluation. A function is strict if it always evaluates its argument. The Haskell report states: "Function application in Haskell is non-strict; that is, a function argument is evaluated only when required."1 The caller passes an unevaluated expression, and the function evaluates it only if a path through the body uses it. So a function can ignore an argument whose evaluation would fail or never end.

Thunks and sharing. An implementation represents an unevaluated expression as a thunk: code to compute the value, and the environment that the code needs, as in a closure. When a program forces the thunk, it runs the code and replaces the thunk with the result. SICP describes this step for streams: "The first time the memoized procedure is run, it saves the computed result. On subsequent evaluations, it simply returns the result." It adds: "The memoizing optimization is also known as call-by-need."2 Without memoization, the same mechanism is call by name, which evaluates the expression again on each use. See parameter passing.

Demand-driven pipelines. When each stage of a pipeline is lazy, the last stage drives the work. SICP calls this "demand-driven" programming, "whereby each stage in the stream process is activated only enough to satisfy the next stage."2 The stages run interleaved, element by element, and not one after another. This is why take(3) on an infinite sequence ends: the consumer stops asking.

Modularity. John Hughes argued that laziness is a kind of glue between program parts. It makes it practical "to modularize a program as a generator that constructs a large number of possible answers, and a selector that chooses the appropriate one."3 The generator does not need to know when to stop, and the selector does not need to know how the answers are made.

Forcing. A lazy language still needs a way to force evaluation, for example to stop a large chain of thunks from building up. Haskell has seq, and the report states that "seq is usually introduced to improve performance by avoiding unneeded laziness."1

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CAbsent
C#Standard library
JavaScriptNative
TypeScriptNative
GoIdiom
RustStandard library
KotlinStandard libraryThe lazy delegate computes a property on first access, and Sequence runs its intermediate operations lazily; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query states the result, and the optimizer decides when and if each part is evaluated.
BashIdiom
PowerShellIdiomThe pipeline passes objects one at a time, and Select-Object -First stops the earlier commands when it has enough objects; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no evaluation of expressions. Alternative: The loading="lazy" attribute delays the fetch of an image or an iframe until it is near the viewport.
CSSDoes not applyCSS has no evaluation of expressions.
Regular expressionsDoes not applyA regular expression has no evaluation of expressions; lazy quantifiers such as *? control the length of a match.
Language Verdict Mechanism
Python stdlib generators, itertools, functools.cached_property
JavaScript native generator functions, iterator helpers, self-replacing getters
TypeScript native as JavaScript, Generator<T>
Java stdlib Stream intermediate operations, Supplier
Kotlin stdlib Sequence, by lazy
C# stdlib LINQ deferred execution, yield return, Lazy<T>
Go idiom iter.Seq iterator functions, sync.OnceValue
Rust stdlib iterator adapters, LazyLock, LazyCell
C absent a function pointer with a flag, short-circuit operators
C++ stdlib range adaptors and views, function-local statics
Bash idiom pipelines, && and ||
PowerShell idiom the object pipeline, Select-Object -First
SQL n/a the optimizer decides the order of evaluation
Regex, HTML, CSS n/a no evaluation of expressions

All of these languages are eager for function arguments. Each one has a short-circuit form of and and or, which is the smallest kind of laziness.

Python has generator functions and generator expressions. The documentation describes generators as "a special class of functions that simplify the task of writing iterators", and states that an iterator can produce "an infinite stream of data".4 functools.cached_property computes an attribute "once and then cached as a normal attribute for the life of the instance."5

JavaScript and TypeScript have generator functions. A getter that replaces itself with a data property is the usual lazy property.

Java streams separate intermediate and terminal operations, and "Intermediate operations are always lazy."6 Kotlin sequences are the lazy form of collections: "actual computing happens only when the result of the whole processing chain is requested."7

C# LINQ uses deferred execution, which "means that the operation isn't performed at the point in the code where the query is declared. The operation is performed only when the query variable is enumerated".8 Lazy<T> gives lazy initialization, in which the creation of an object "is deferred until it is first used."9

Go has iterator functions that a for range loop drives, and sync.OnceValue for lazy initialization.

Rust iterators "are lazy, meaning they have no effect until you call methods that consume the iterator to use it up."10 LazyLock makes a lazy global value.

C has no laziness except the short-circuit operators. C++ range adaptors "are applied to views lazily", and they can be composed into pipelines.11

Bash pipelines are demand-driven: each command blocks when the next command does not read, and an exit of the reader stops the writer.

PythonGitHub
from functools import cached_property
from itertools import count, islice


def squares():
    for n in count(1):
        yield n * n


print(list(islice(squares(), 5)))


class Report:
    @cached_property
    def summary(self):
        print("building summary")
        return "3 errors"


report = Report()
print("report created")
print(report.summary)
print(report.summary)
Output
[1, 4, 9, 16, 25]
report created
building summary
3 errors
3 errors
  • Verdict: stdlib. Python evaluates arguments eagerly. Generators, generator expressions, range, map, filter, zip and itertools produce values on demand.
  • functools.cached_property computes an attribute on first access and stores it. and, or and the conditional expression evaluate only the operands that they need.

This code runs but gives a wrong answer on purpose.

lines = (line.upper() for line in ["a", "b"])
print(list(lines))
print(list(lines))
Output
['A', 'B']
[]

A generator produces its values one time. The second pass finds it empty and gives no error. Use a list if the program must read the values more than once, or make a new generator for each pass.

#include <iostream>
#include <ranges>

int main() {
    auto odd_squares = std::views::iota(1)
        | std::views::transform([](int n) { return n * n; })
        | std::views::filter([](int n) { return n % 2 == 1; })
        | std::views::take(3);

    for (int n : odd_squares) {
        std::cout << n << " ";
    }
    std::cout << "\n";
}
Output
1 9 25 
  • Verdict: stdlib. C++ evaluates eagerly. The range adaptors in <ranges> make views, which compute each element when the loop reads it, so an infinite iota is safe.
  • &&, || and ?: evaluate only the operands that they need. A lambda with no parameters is a thunk, and a function-local static variable is initialized on the first call.
JavaGitHub
import java.util.function.Supplier;
import java.util.stream.Stream;

public class Main {
    static <T> Supplier<T> memoize(Supplier<T> source) {
        return new Supplier<>() {
            private T value;
            private boolean ready;

            public T get() {
                if (!ready) {
                    value = source.get();
                    ready = true;
                }
                return value;
            }
        };
    }

    public static void main(String[] args) {
        Stream<Integer> evens = Stream.iterate(1, n -> n + 1)
                .peek(n -> System.out.println("visit " + n))
                .filter(n -> n % 2 == 0);
        System.out.println("nothing visited yet");
        System.out.println(evens.limit(2).toList());

        Supplier<String> config = memoize(() -> {
            System.out.println("reading config");
            return "debug";
        });
        System.out.println(config.get() + " " + config.get());
    }
}
Output
nothing visited yet
visit 1
visit 2
visit 3
visit 4
[2, 4]
reading config
debug debug
  • Verdict: stdlib. Java evaluates arguments eagerly. The intermediate operations of a Stream, such as map, filter and peek, are lazy, and nothing runs until a terminal operation, such as toList.
  • A Supplier is a thunk. The standard library has no memoizing supplier, so programs write one or use a library. The memoizer above is not safe for use by many threads.

This code runs but gives a wrong answer on purpose.

import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Stream<String> names = Stream.of("a", "b");
        System.out.println(names.count());
        try {
            System.out.println(names.count());
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
2
stream has already been operated upon or closed

A stream can be consumed one time. Keep the source collection and make a new stream for each pass.

#include <stdbool.h>
#include <stdio.h>

struct lazy_int {
    bool ready;
    int value;
    int (*compute)(void);
};

static int expensive(void) {
    puts("computing");
    return 42;
}

static int force(struct lazy_int *lazy) {
    if (!lazy->ready) {
        lazy->value = lazy->compute();
        lazy->ready = true;
    }
    return lazy->value;
}

int main(void) {
    struct lazy_int answer = {.compute = expensive};
    puts("nothing computed yet");
    printf("%d\n", force(&answer));
    printf("%d\n", force(&answer));
    return 0;
}
Output
nothing computed yet
computing
42
42
  • Verdict: absent. C evaluates eagerly. A struct with a function pointer and a flag is a memoized thunk, and the caller forces it.
  • &&, || and ?: are the lazy operators of C.
var numbers = new List<int> { 1, 2, 3 };
var doubled = numbers.Select(n => n * 2);
numbers.Add(4);
Console.WriteLine(string.Join(",", doubled));

var config = new Lazy<string>(() =>
{
    Console.WriteLine("reading config");
    return "debug";
});
Console.WriteLine(config.IsValueCreated);
Console.WriteLine(config.Value + " " + config.Value);

static IEnumerable<int> Naturals()
{
    for (int n = 1; ; n++)
    {
        yield return n;
    }
}

Console.WriteLine(string.Join(",", Naturals().Where(n => n % 3 == 0).Take(3)));
Output
2,4,6,8
False
reading config
debug debug
3,6,9
  • Verdict: stdlib. Most LINQ operators use deferred execution: the query runs when code enumerates it, and it reads the source at that time. yield return makes a lazy sequence.
  • Lazy<T> computes a value on first access, and it is safe for use by many threads by default.

This code runs but gives a wrong answer on purpose.

int calls = 0;
var query = new[] { 1, 2, 3 }.Select(n =>
{
    calls++;
    return n * n;
});
Console.WriteLine(query.Sum());
Console.WriteLine(query.Max());
Console.WriteLine($"selector ran {calls} times");
Output
14
9
selector ran 6 times

Each enumeration runs the query again. If the query is slow or has side effects, call ToList() one time and use the list.

JavaScriptGitHub
function* naturals() {
  for (let n = 1; ; n++) {
    console.log("computing", n);
    yield n;
  }
}

function* take(items, count) {
  if (count <= 0) return;
  for (const item of items) {
    yield item;
    if (--count === 0) return;
  }
}

const firstTwo = take(naturals(), 2);
console.log("nothing computed yet");
console.log([...firstTwo]);

const settings = {
  get theme() {
    console.log("loading theme");
    const value = "dark";
    Object.defineProperty(this, "theme", { value });
    return value;
  },
};
console.log(settings.theme, settings.theme);
Output
nothing computed yet
computing 1
computing 2
[ 1, 2 ]
loading theme
dark dark
  • Verdict: native. Generator functions produce values on demand, and the iterator helpers of newer engines, such as Iterator.prototype.take, chain lazy steps.
  • A getter that replaces itself with a plain property is the usual lazy and cached property. &&, || and ?? evaluate the right operand only when they need it.
TypeScriptGitHub
function* fibonacci(): Generator<number, never, unknown> {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

function firstWhere<T>(items: Iterable<T>, test: (item: T) => boolean): T | undefined {
  for (const item of items) {
    if (test(item)) return item;
  }
  return undefined;
}

console.log(firstWhere(fibonacci(), (n) => n > 100));
Output
144
  • Verdict: native. As JavaScript. The type Generator<T, TReturn, TNext> describes the values that a generator yields and returns.
package main

import (
	"fmt"
	"iter"
	"sync"
)

func naturals() iter.Seq[int] {
	return func(yield func(int) bool) {
		for n := 1; ; n++ {
			if !yield(n) {
				return
			}
		}
	}
}

var config = sync.OnceValue(func() string {
	fmt.Println("reading config")
	return "debug"
})

func main() {
	for n := range naturals() {
		if n*n > 50 {
			fmt.Println(n)
			break
		}
	}
	fmt.Println(config(), config())
}
Output
8
reading config
debug debug
  • Verdict: idiom. Go evaluates eagerly. An iterator function of type iter.Seq produces values only while the loop asks for them, and break stops the producer.
  • sync.OnceValue returns a function that computes its value on the first call, and it is safe for use by many goroutines.
RustGitHub
use std::sync::LazyLock;

static CONFIG: LazyLock<String> = LazyLock::new(|| {
    println!("reading config");
    String::from("debug")
});

fn main() {
    let squares = (1..).map(|n| n * n).filter(|n| n % 2 == 1);
    let first: Vec<u64> = squares.take(3).collect();
    println!("{first:?}");

    println!("program started");
    println!("{} {}", *CONFIG, *CONFIG);
}
Output
[1, 9, 25]
program started
reading config
debug debug
  • Verdict: stdlib. Rust evaluates eagerly, but iterator adapters such as map and filter are lazy. The Rust book states that iterators "have no effect until you call methods that consume the iterator".
  • LazyLock and LazyCell compute a value on first access. OnceLock stores a value that code sets one time.
  • An adapter that nothing consumes does nothing, and the compiler warns about it, because the adapters are #[must_use].
BashGitHub
yes "line" | head -n 3
seq 1 1000000000 | awk '$1 * $1 > 50 { print; exit }'

config=""
get_config() {
  if [[ -z $config ]]; then
    echo "reading config" >&2
    config="debug"
  fi
}
get_config
get_config
echo "$config"
Output
line
line
line
8
debug
  • Verdict: idiom. The stages of a pipeline run at the same time, and each stage reads only as much input as it needs. When head exits, yes gets SIGPIPE and stops, so an endless producer is safe.
  • && and || run the right command only when the status of the left command requires it.

Lazy by default or lazy on request. Haskell and Miranda are lazy by default and offer strictness with seq, bang patterns and strict fields. Most languages are eager by default and offer laziness through special types. Scala has lazy val, and Swift has lazy var.

Lazy initialization. A single value that is computed on first use is the most common form in eager languages. When many threads can make the first request, the implementation must make sure that only one of them computes the value.

Generators and coroutines. A generator is a function that can pause after each value. It gives lazy sequences in an eager language, and it keeps its state between requests. See iterators.

Short-circuit evaluation. &&, ||, ?? and the conditional operator evaluate the second operand only when the first one does not decide the result. See order of evaluation.

Lazy loading. A program or a web page can delay the load of code, data or images until the user needs them. The name is the same, and the idea is the same, at the level of resources.

Futures. A future also stands for a value that is not computed yet. A future usually starts its work at once, in parallel. A lazy value starts its work only when a program asks for the result.

Pitfalls

Side effects at unknown times. With laziness, the time when an effect happens depends on when code asks for the value. Hughes wrote that lazy evaluation and side effects do not combine well, because a programmer would need to know much about the context to predict the order of the effects, or if they occur at all.3 Keep lazy code free of side effects, or force it at a known point.

Sources that change. A deferred query reads its source when it runs, not when it is defined. If the source changes between the two times, the result includes the change.

Single-use sequences. A Python generator, a Java stream and many iterators can be consumed only once. A second pass gets nothing, or an exception.

Repeated work. A lazy sequence that is not memoized runs again for each consumer. In C#, two enumerations of the same LINQ query run the query and its side effects twice.

Space leaks. In a lazy language, a chain of unevaluated thunks can hold much more memory than the value it describes. The classic example is a sum over a long list with foldl, which builds a thunk for each element before it adds any of them. Strict versions, such as foldl', and seq prevent this.

Hidden cost and errors. An expression that looks cheap can force a large computation, and an error can appear far from the code that caused it, when a thunk is finally forced.

Cost

A thunk is a heap object with code and an environment, and the force operation checks if the value is ready. In a lazy language, the compiler uses strictness analysis to find arguments that are always needed and evaluates them eagerly, which removes most thunks. In eager languages, lazy iterators often cost less than eager collections, because they do not build the intermediate lists. They can also stop early, so a search through a large or infinite sequence does only the work needed for the result.

History

The ideas came from call by name in Algol 60. SICP states that "the use of this mechanism to implement streams was first described by Landin (1965). Delayed evaluation for streams was introduced into Lisp by Friedman and Wise (1976). In their implementation, cons always delays evaluating its arguments, so that lists automatically behave as streams."2 Christopher Wadsworth described call by need, the memoized form, in his thesis on the lambda calculus in 1971. Peter Henderson and James Morris described a lazy evaluator for a Lisp-like language in 1976. David Turner made laziness the default in SASL, KRC and Miranda, and Haskell, in 1990, followed Miranda. John Hughes argued for the value of laziness in "Why Functional Programming Matters".3 Eager languages later took the parts of laziness that work well with side effects: generators, lazy streams, deferred queries and lazy initialization.

References

  1. Haskell 2010 Language Report, Predefined Types and Classes, 6.2 Strict Evaluation
  2. Structure and Interpretation of Computer Programs, H. Abelson and G. J. Sussman, second edition, MIT Press, 3.5 Streams
  3. Why Functional Programming Matters, J. Hughes, in Research Topics in Functional Programming, D. Turner, editor, Addison-Wesley, 1990, 4 Gluing Programs Together
  4. Functional Programming HOWTO, Python 3.14 documentation, Iterators and Generators
  5. functools, Python 3.14 documentation, functools.cached_property
  6. java.util.stream package summary, Java SE 25 API documentation, Stream operations and pipelines
  7. Sequences, Kotlin documentation, introduction
  8. Introduction to LINQ Queries in C#, Microsoft Learn, Deferred
  9. Lazy Initialization, .NET documentation, Microsoft Learn, introduction
  10. The Rust Programming Language, 13.2 Processing a Series of Items with Iterators, Rust 1.99.1, introduction
  11. Ranges library, cppreference.com, introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/2EHE06/text.yaml