hjk41的日志

Avatar

More Effective C++ 17: Consider using lazy evaluation

Lazy evaluation sometimes saves resources, and it is applicable in a lot of areas. Here's three of them:

1. Reference Counting


String a="hello";
String b=a;
cout<<b<<endl;


Here, b is a copy of a, but they are never changed. So we can just implement b as a reference to a, and wait till we really need to change one of them.

2. Lazy Fetching


class LargeObject {                        // large persistent objects
public:
  LargeObject(ObjectID id);                // restore object from disk

  const string& field1() const;            // value of field 1
  int field2() const;                      // value of field 2
  double field3() const;                   // ...
  const string& field4() const;
  const string& field5() const;
  ...

};

void restoreAndProcessObject(ObjectID id)
{
  LargeObject object(id);

  if (object.field2() == 0) {
    cout << "Object " << id << ": null field2.\n";
  }
}


Consider a very large object, which will take a lot of time to construct. If we construct a new object only to read its OjbectID, then most of our effort spent constructing the members will be wasted. So we can consider postponing the construction of the other member variables untill we use them.

3. Lazy Expression Evaluation


Matrix a(1000,1000);
Matrix b(1000,1000);
Matrix c(1000,1000);

cout<<c[10][10]<<endl;


Here, we need only one element from the matrix c. So we don't have to evaluate all the elements of c. That's lazy expression evaluation.

评论已关闭