C++ Optimizations

Labels: , , , , |

Avoid Expensive Operations
Addition is cheaper than multiplication and multiplication is cheaper than division. Factor out expensive operations whereever possible.

Initialize on Declaration
Whereever possible, initialize variables at the time they're declared. For example,

TMyClass myClass = data;

is faster than

TMyClass myClass;
myClass = data;

Declaration then initialization invokes the object's default constructor then its assignment operator. Initializing in the declaration invokes only its copy constructor.

Pass By Reference
Always try to pass classes by reference rather than by value. For example, use

void foo(TMyClass &myClass)

rather than

void foo(TMyClass myClass)

Delay Variable Declarations
Leave variable declarations right until the point when they're needed. Remember that when a variable is declared its constructor is called. This is wasteful if the variable is not used in the current scope.

Use 'op='
Wherever possible, use 'op=' in favour of 'op'. For example, use

myClass += value;

rather than

myClass = myClass + value;

The first version is better than the second because it avoids creating a temporary object.

Inline Small Functions
Small, performance critical functions should be inlined using the inline keyword, e.g.,

inline void foo()

This causes the compiler to duplicate the body of the function in the place it was called from. Inlining large functions can cause cache misses resulting in slower execution times.

Use Nameless Classes
Whereever possible, use nameless classes. For example,

foo(TMyClass("abc"));

is faster than

TMyClass myClass("abc");
foo(myClass);

because, in the first case, the parameter and the class share memory.

0 comments: