6 Lazy evaluation

 

This chapter covers

  • Calculating values when they’re needed
  • Caching values of pure functions
  • Modifying the quicksort algorithm to sort only parts of the collection
  • Using expression templates for lazy evaluation of expressions
  • Representing infinite or near-infinite structures

Calculations take time. Say you have two matrices—A and B—and you’re told you may need their product at some point. One thing you could do is to immediately calculate the product, and it’ll be ready when you need it:

auto P = A * B;

The problem is that you may end up not needing the product at all—and you wasted your precious CPU cycles calculating it.

An alternative approach is to say if someone needs it, P should be calculated as A * B. Instead of doing the calculation, you’re just defining it. When a part of your program needs the value of P, you’ll calculate it. But not before.

You usually define calculations by creating functions. Instead of P being a value that holds the product of A and B, you can turn it into a lambda that captures A and B and returns their product when invoked:

auto P = [A, B] {
    return A * B;
};

If someone needs the value, they need to call it like a function P().

6.1 Laziness in C++

6.2 Laziness as an optimization technique

6.2.1 Sorting collections lazily

6.2.2 Item views in the user interfaces

6.2.3 Pruning recursion trees by caching function results

6.2.4 Dynamic programming as a form of laziness

6.3 Generalized memoization

6.4 Expression templates and lazy string concatenation

6.4.1 Purity and expression templates

Summary

sitemap