Friday, August 17, 2007

The peril of smart pointers in C++

It's a general pattern I've seen in several large C++ code bases. Either through the standard std::auto_ptr, or from some custom contrivance, a block of code throws around smart pointers and memory allocations without really thinking about it. auto_ptr makes it easy to return a pointer, and then throw it away without worry because the memory will be easily deallocated. So, I find myself reading a lot of code like this:

class Rectangle;
...
std::auto_ptr factoryMethod();
...
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: