Temporary Variables: Chasing Temporaries Away - Details, details… what’s that… small print?
(Page 4 of 5 )
Taking one last look at our FindClosest function, there are two more points to be made about optimization. The first one relates to the termination condition in the for-loop:
for (nmeIt=enemies.begin(); nmeIt!=enemies.end(); nmeIt++) {...}
Remember that any for loop can be written as a while loop:
list<Enemy>::iterator nmeIt=enemies.begin();
while ( nmeIt != enemies.end() ) {
NmeIt++;
}
Because the for-loop combines three separate steps into one statement, it can become easy to overlook the fact that the terminating condition for the loop ( nmeIt != enemies.end() ) is going to be evaluated at the start of every iteration of that loop.
Since the end of our list is not going to change, we might as well cache the object we are going to use in the termination condition. This saves us from the need to construct and destruct a temporary termination condition object every iteration.
list<Enemy>::iterator nmeIt;
list<Enemy>::iterator lastEnemy=enemies.end()
for (nmeIt=enemies.begin(); nmeIt!=lastEnemy; nmeIt++) { ... }
The second optimization relates to the way we increment our iterator. There are two operators to choose from: the prefix and the postfix increment operators.
Here is how you would implement them for a Counter class:
Counter const& Counter::operator++() {
++mValue;
return *this;
}
Counter const Counter::operator++(int) {
Counter temp(*this);
++mValue;
return temp;
}
While we only need to increment the iterator, it does make a difference whether we choose a prefix or a postfix operator. I tested these operators with the MyClass test class from the first article and was quite surprised to see that the compiler had optimized neither the local nor the temporary objects away (even with Full Optimization switched on!) for the post-increment operator:
Pre and Post Increment test.
‘Prefix’ – Constructor called.
‘Prefix’ – Prefix Increment Operator called.
Done.
‘Postfix’ – Constructor called.
unnamed object – Copy Constructor called.
‘Postfix’ – Postfix Increment Operator called.
Unnamed object – Copy Constructor called.
Unnamed object – Destructor called.
Unnamed object – Destructor called.
Now there is a temporary object you certainly do not need!
As a final word about optimization, I would like to stress that it is good to keep optimization in mind, but also to remember that it is only useful after you have detected what is causing a performance problem. Optimizing parts of your program that are not performance critical is a waste of your (valuable) time.
Next: Help the compiler help you >>
More C++ Articles
More By J. Nakamura