hjk41的日志

Avatar

More Effecitve C++ 18: Amortize the cost of expected computation

We disscussed lazy evaluation in the last Item, now we are disscussion over-eager evaluation.
Lazy evaluation is used to data that is rarely used. On the contrary, over-eager evaluation is for the data that is frequently used.
In over-eager evaluation, you prepare something before they are needed. For example, consider a data collection class that provides min, max and avg of the collection:


template<class NumericalType>
class DataCollection {
public:
  NumericalType min() const;
  NumericalType max() const;
  NumericalType avg() const;
  ...
};


If you believe that these three member functions will be called fequently, you can improve the performance of them by using over-eager evaluation. Every time a data value is added to the data collection, the min, max, and avg are calculated and stored in member variables. When the three member functions are called, they can just return the value of the corresponding member variable.

Another tactics of over-eager evaluation is caching and prefetching, which is widely used in computer design. I will not disscuss it in detail.

评论已关闭