C++ Optimizations
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 ListsAlways use initialization lists in constructors. For example, use
rather than
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 LoopsWhereever possible, count down to zero rather than up to n. For example, use
rather than
The test is done every iteration and it's faster to test against zero than anything else. Note also that
is faster than
when it appears in the third part of the for loop statement. |
Use 'int'Always use the |
Make Local Functions StaticAlways declare local functions as static, e.g.,
This means they will not be visible to functions outside the |
Optimize If StatementsFactor out jumps. For example, use
rather than
Use a profiler and good judgement to decide if undoing the bar() operation is faster than jumping. |
Optimize Switch StatementsPut the most common cases first. |
Avoid Expensive OperationsAddition is cheaper than multiplication and multiplication is cheaper than division. Factor out expensive operations whereever possible. |
Initialize on DeclarationWhereever possible, initialize variables at the time they're declared. For example,
is faster than
Declaration then initialization invokes the object's default constructor then its assignment operator. Initializing in the declaration invokes only its copy constructor. |
Pass By ReferenceAlways try to pass classes by reference rather than by value. For example, use
rather than
|
Delay Variable DeclarationsLeave 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
rather than
The first version is better than the second because it avoids creating a temporary object. |
Inline Small FunctionsSmall, performance critical functions should be inlined using the inline keyword, e.g.,
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 ClassesWhereever possible, use nameless classes. For example,
is faster than
because, in the first case, the parameter and the class share memory. |
没有评论:
发表评论