C++ tip 15: Delay construction of objects until they are needed
Whenever you call a constructor/destructor you are incurring a cost. This cost is justify as long as you are using the object. But not when you won't ever use the object. For example, take a look at the function below:
void function(int arg){
Point point; //Object Point
if(arg==0){
return;
}
}
Once you enter the function, the first thing we do is create an instance of Point, thus calling a constructor. Assume that arg is equal to zero. This will forces us to leave the function without ever making use of the object Point. Thus, we incurred the cost of calling a constructor/destructor for not reason at all.
Therefore, you would be better off postponing Point's definition until you know you'll need it. For example:
void function(int arg){
if(arg==0){
return;
}
Point point; //postpone the construction of Point
//..continue on
}
How about when you are working with loops? When should you define an object, outside the loop or inside the loop?
Let's take a look at Approach A:
//Approach A: define outside loop
Point p;
for(int i=0;i<n;i++){
//use p here
}
The cost of Approach A is:
- 1 constructor + 1 destructor + n assignments
Now, let's take a look at Approach B:
//Approach B: define inside loop
for(int i=0;i<n;i++){
Point p;
//use p here
}
The cost of Approach B is:
- n constructors + n destructors
In his book Effective C++, Scott Meyers states that for cases where you know that assignment costs less than a constructor/destructor pair, Approach A is more efficient. Thus, unless you know that (1) assignment is less expensive than constructor/destructor pair and (2) you are dealing with performance-sensitive part of a code, you should default to using Approach B.
So here is a tip:
Delay construction of objects until they are truly need it.