1- Use 'int'
Always use the int data type instead of char or short wherever possible. int is always the native type for the machine.
2- 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.
3- Avoid Expensive Operations
Addition is faster than multiplication and multiplication is faster than division. Factor out expensive operations whereever possible.
4- 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)
5- 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.
6- 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.
7- 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.
No comments:
Post a Comment