Tips for Optimizing C/C++ Code
https://people.cs.clemson.edu/~dhouse/courses/405/papers/optimize.pdf
- Remember Ahmdal's Law. This is often phrased as: "make the common case fast and the rare case correct."
- Code for correctness first, then optimize!
- People I know who write very efficient code say they spend at least twice as long optimizing code as they spend writing code.
- Jumps/branches are expensive. Minimize their use whenever possible.
- Think about the order of array indices.
- Think about instruction-level-parallelism.
- Avoid/reduce the number of local variables.
- Reduce the number of function parameters.
- Pass structures by reference, not by value.
- If you do not need a return value from a function, do not define one.
- Try to avoid casting where possible.
- Be very careful when declaring C++ object variables.
- Make default class constructors as lightweight as possible.
- Use shift operations >> and << instead of integer multiplication and division, where possible.
- Be careful using table-lookup functions.
- For most classes, use the operators += , -= , *= , and /= , instead of the operators + , - , * , and / .
- For basic data types, use the operators + , - , * , and / instead of the operators += , -= , *= , and /= .
- Delay declaring local variables.
- For objects, use the prefix operator `(
)`.obj)` instead of the postfix operator `(obj - Be careful using templates.
- Avoid dynamic memory allocation during computation.
- Find and utilize information about your system’s memory cache.
- Try to early loop termination and early function returns.
- Simplify your equations on paper!
- The difference between math on integers, fixed points, 32-bit floats, and 64-bit doubles is not as big as you might think.
- Consider ways of rephrasing your math to eliminate expensive operations.