Back to C++ Optimization Techniques

1: General Strategies

There's a right way and a wrong way to do optimization. Here's some strategies common to all programming endeavors that work and don't work.

1.1: Optimization Strategies that Bomb

1.2: Optimization Strategies that Work

1.3: Example of Selecting the Proper Algorithm: Swapping

Swapping objects is a common operation, especially during sorting. The standard C++ swapping function is very simple.

template <class T> void MySwap(T& a, T& b)
    {
    T t = a; // copy ctor
    a = b;   // assignment operator
    b = t;   // assignment operator
    }        // destructor (element t)

Swapping is so simple that we really only need a single function to handle it, right? Not necessarily. Often an object can provide its own swapping method that is considerably faster than calling the object's constructor, assignment operator (twice), and destructor. In fact, with STL, there are many specialized swap routines, including string::swap, list::swap, and so forth.

As you can see, calling STL swap is the same as using the MySwap algorithm above. However, for specialized classes, like strings, swapping has been optimized to be 6-7 times faster. For the bitmap object, which has extremely expensive constructors and assignment operators, the bitmap::swap routine is over 8000 times faster!

Back to C++ Optimization Techniques