class Rectangle;
...
std::auto_ptr
...
handleRectangle(factoryMethod());
There are several annoyances to a good C++ programmer here, but there's also something very hidden and illusive that most people would never think about - allocating and deallocating memory isn't that cheap. Now, it's not a very expensive operation either, but handling a memory allocation off the heap can easily take up to 500% the amount of time as allocating off the stack - and that can easily increase if your code is doing a lot of it.
Using named returns provides an excellent alternative. In a few example blocks of code I tested with some speed critical operations, I tested a 6 fold increase in speed when using named returns versus passing around pointers. The use of a named return allows you to return and use temporary objects, without worrying about copy constructor calls.
So, in summary, the next time you are about to throw in a 'new' keep in mind that allocating memory using new (especially in a tight loop), is a LOT slower than just creating a new variable off the stack.
No comments:
Post a Comment