3.5.4 How Can I Make My Code Faster?

To a large degree, smaller code is faster code, so efforts to reduce code size often decrease execution time (see Section 2.6.2 “How Can I Make My Code Smaller?” and Section 2.6.7 “How Can I Make My Interrupt Routine Faster?”). However, there are ways some sequences can be sped up at the expense of increased code size.

When level O3 optimizations have been selected, the compiler favors optimizations that reduce the program’s execution time (but which might increase the program’s size), whereas level Os optimizations are designed to purely reduce code size (see 4.6.6 Options for Controlling Optimization).

Some library multiplication routines operate faster when one of their operands is a smaller value (see 5.5.3 Multiplication for more information on how to take advantage of this).

Generally, the biggest gains to be made in terms of speed of execution come from the algorithm used in a project. Identify which sections of your program need to be fast. Look for loops that might be linearly searching arrays and choose an alternate search method such as a hash table and function. Where results are being recalculated, consider if they can be cached.