Rule 5. The First Lesson of Optimization Is Don’t Optimize

My favorite programming task is optimization. Usually that means making some code system run faster, though sometimes I’m optimizing memory usage or network bandwidth or some other resource.

It’s my favorite task because it’s simple to measure success. For most coding work, what constitutes success is fuzzy. Books like this one try hard to define what good code or a good system looks like, but what makes a line of code good is always imprecise.

That’s not true for optimization. There, the answers are crisper. If you’re trying to make something run faster, you can measure your success directly. The same goes for the cost of that success in terms of increased code size or complexity. No worrying about semi-defined long-term benefits, no trusting that someone reading your new code a few years from now will understand it immediately and be swept away in a wave of emotional appreciation for you as a programmer. Just immediate, tangible results.

I’m not alone in this fondness for optimization. In fact, it’s seductive enough to have prompted the one programming adage that every programmer knows:

Premature optimization is the root of all evil.

That’s not the whole quote, by the way. The original version, as written down by Donald Knuth in 1974, is more nuanced:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

It’s important to note the context.1 In 1974, ...

Get The Rules of Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.