C++ Optimizations

Labels: , , , , |

These optimizations are fairly easy to apply to existing code and in some cases can result in big speedups. Remember the all-important maxim though, the fastest code is code that isn't called.

Use Initialization Lists
Always use initialization lists in constructors. For example, use

TMyClass::TMyClass(const TData &data) : m_Data(data)
{
}

rather than

TMyClass::TMyClass(const TData &data)
{
m_Data = data;
}

Without initialization lists, the variable's default constructor is invoked behind-the-scenes prior to the class's constructor, then its assignment operator is invoked. With initialization lists, only the copy constructor is invoked.

Optimize For Loops
Whereever possible, count down to zero rather than up to n. For example, use

for (i = n-1; i >= 0; --i)

rather than

for (i = 0; i <>

The test is done every iteration and it's faster to test against zero than anything else. Note also that

++i

is faster than

i++

when it appears in the third part of the for loop statement.

Use 'int'
Always use the int data type instead of char or short wherever possible. int is always the native type for the machine.

Make Local Functions Static
Always declare local functions as static, e.g.,

static void foo()

This means they will not be visible to functions outside the .cpp file, and some C++ compilers can take advantage of this in their optimizations.

Optimize If Statements
Factor out jumps. For example, use

bar();
if (condition)
{
undoBar();
foo();
}
rather than

if (condition)
{
foo();
}
else
{
bar();
}

Use a profiler and good judgement to decide if undoing the bar() operation is faster than jumping.

Optimize Switch Statements
Put the most common cases first.

0 comments: