Optimize C and C++ Code
Published in
1 min readJun 3, 2017
With the advent of mobile devices, optimizing code has become even more important. Faster applications not only improve the user experience, they also improve battery life.
Optimizing C++ and C Code discusses several techniques that will help improve the performance.
- Premature optimization is the root of all evil
- Adjust structure sizes to power of two
- Place case labels in narrow range
- Place frequent case labels first
- Break big switch statements into nested switches
- Minimize local variables
- Declare local variables in the inner most scope
- Reduce the number of parameters
- Use references for parameter passing and return value for types bigger than 4 bytes
- Don’t define a return value if not used
- Consider locality of reference for code and data
- Locality of reference in multi-dimensional arrays
- Prefer int over char and short
- Define lightweight constructors
- Prefer initialization over assignment
- Use constructor initialization lists
- Do not declare “just in case” virtual functions
- In-line 1 to 3 line functions
- Avoid cascaded function calls
- Prefer preincrement over postincrement
- Define move constructors in C++11
- Use hardware accelerators and SIMD hardware
- Use profile guided optimization