The elements of programming style: Efficiency and instrumentation
Chapter 7: Efficiency and instrumentation
Machines have become increasingly cheap compared to people; any discussion of computer efficiency that fails to take this into account is shortsighted. “Efficiency” involves the reduction of overall cost – not just machine time over the life of the program, but also time spent by the programmer and by the users of the program.
A clean design is more easily modified as requirements change or as more is learned about what parts of the code consume significant amounts of execution time. A “clever” design that fails to work or to run fast enough can often be salvaged only at great cost. Efficiency does not have to be sacrificed in the interest of writing readable code – rather, writing readable code is often the only way to ensure efficient programs that are also easy to maintain and modify.
- Make it right before you make it faster
- Keep it right when you make it faster
- Make it clear before you make it faster
This brings us to another important point: simplicity and clarity are often of more value than the microseconds possible saved by clever coding.
- Don’t sacrifice clarity for small gains in “efficiency”
- Let your compiler do the simple optimization
- Don’t straint to re-use code; reorganize instead
- Make sure special cases are truly special
- Keep it simple to make it faster
- Don’t diddle code to make it faster – Find a better algorithm
- Instrument your program. Measure before making “efficiency” changes
The cost of computing hardware has steadily decreased; software cost has steadily increased. “Efficiency” should concentrate on reducing the expensive parts of computing. To summarize the main points of this chapter.
(1) If a program is wrong, it doesn’t matter how fast it is. Get it right before you start to “improve” it.
(2) Keep code clean and straightforward – don’t try to make it fast while coding. Premature optimization is the root of all evil.
(3) Don’t worry about optimizing every little calculation. Let the compiler do it for you.
(4) Worry about the algorithm, not about the details of code. Remember that data structure can profoundly affect how an algorithm must be implemented.
(5) Instrument a program during construction. Measure before deciding on “efficiency” changes. Leave the instrumentation in as the program evolves.