Premature optimization is the optimizing of code for performance reasons before the code has been measured or profiled to determine if the optimization will actually be beneficial.
Premature optimization is a term coined by Donald Knuth. In general terms, it means "the optimizing of code for performance reasons before the code has been measured or profiled to determine if the optimization will actually be beneficial."
The term "premature optimization" comes from a quote from Knuth's paper "Structured Programming with goto Statements, in which he states:
There is no doubt that the grail of efficiency leads to abuse. Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
Yet we should not pass up our opportunities in that critical 3 %. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified. It is often a mistake to make a priori judgments about what parts of a program are really critical, since the universal experience of programmers who have been using measurement tools has been that their intuitive guesses fail.
This quote is often shortened to simply
Premature optimization is the root of all evil
and sometimes used (in its abbreviated form) as an excuse not to optimize code at all, or to eschew critical design decisions involving the choice of appropriate data structures and sensible programming practices.
The best practices embodied by Knuth's observation are these:
- Measure code performance first, and then
- Optimize only the hot spots, those parts of the code that are causing the greatest impact on performance.
Premature optimization negatively affects debugging and maintenance, because optimized code is typically more difficult to read and understand. Premature optimization can actually slow down a program because the optimizations are confounding the optimizations that the compiler already provides.