Being lazy in C++
In the realm of C++, laziness is a powerful concept worth exploring. Lazy initialization, the practice of deferring the creation of an object until it is truly required, can yield performance benefits. This technique came to light during a client discussion about a mantra for C++ programming: "You don't pay for what you don't use."
The crux of the issue lies in the fact that certain functions, like `value_or`, force evaluation of their arguments before execution. This inefficiency persists across various STL implementations, including MSVC's. The `value_or` function exhibits this behavior, triggering computation in both the successful and fallback branches.
To address this, a generic solution is needed. One such approach involves creating a `Lazy` helper, which wraps the computation behind a conversion operator. This operator only triggers the computation when the value is actually materialized, thus avoiding unnecessary work. However, this simple implementation has its drawbacks, as it recomputes the result on each conversion and lacks type safety.
In subsequent articles, we will delve deeper into creating a more robust `Lazy` type that memoizes its result and only converts to the type returned by the initializer, while also measuring its runtime cost.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.