There are situations in C++ when it is good to return the result of a function by value rather than by reference. There is usually a price to be paid, however...unless the compiler can be made to help. Jun Nakamura explains.
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:
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.
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:
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:
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.