Chapter 13 Key PointsCoding optimizations are local in scope and do not necessitate understanding of overall program design. This is a good place to start when you join an ongoing project whose design you don't yet understand.
The fastest code is the one that's never executed. Try the following to bail out of a costly computation:
Are you ever going to use the result? It sounds silly, but it happens. At times we perform computation and never use the results.
Do you need the results now? Defer a computation to the point where it is actually needed. Premature computations may never be used on some execution flows.
Do you know the result already? We have seen costly computations performed even though their results were available two lines above. If you already computed it earlier in the execution flow, make the result available for reuse.
Sometimes you cannot bail out, and you just have to perform the computation. The challenge now is to speed it up:
Is the computation overly generic? You only need to be as flexible as the domain requires, not more. Take advantage of simplifying assumptions. Reduced flexibility increases speed.
Some flexibility is hidden in library calls. You may gain speed by rolling your own version of specific library calls that are called often enough to justify the effort. Familiarize yourself with the hidden cost of those library and system calls that you use.
Minimize memory management calls. They are relatively expensive on most compilers.
If you consider the set of all possible input data, 20% of it shows up 80% of the time. Speed up the processing of typical input at the expense of other scenarios.
The speed differential among cache, RAM, and disk access is significant. Write cache-friendly code.