See all glossary terms

Premature Optimization

Premature optimization is the act of optimizing code before it's necessary. It's a common pitfall in software development that can lead to more problems than it solves.
As programmers, we tend to want to future-proof our code by catering for all possible future problems. This is a noble goal, but almost always misguided.
There are three important reasons why premature optimization will not yield the results you want:

Making future changes hard

The future is uncertain, with infinite possibilities, and the problems you think you'll have in the future will most probably not even happen. However, different problems, that you didn't anticipate, will arise. Those problems will be made much harder to solve because of the abstractions you'll have introduced, which will make your code harder to change.

Making performance worse

Often, by thinking we're making performance better, we're actually making it worse. This is because even for veterans and seniors, our intuition about code performance are often very wrong. We cannot predict what is the best code. We need to measure it.
The only way to actually know if you can improve performance is to be scientific about it: measure, optimize, measure again. Otherwise, it's not optimization, it's just faith and guesswork.

Increasing complexity

Every time you optimize code, you're making it more complex. This complexity will make the code harder to read and understand. This will make it harder to maintain, debug, extend, and test.
For that reason, each added bit of complexity should be duly considered, and the trade-offs weighed. If you're not sure that the optimization is necessary, it's better to keep the code simple and readable. To be sure, you need to be relatively advanced in your project; therefore, you cannot take those decisions upfront.

Wasting time and making us sad

Since optimizing early is likely to be useless, make the code worse, increase complexity for no benefit, and make future changes harder, it's a waste of time. But it's not just a pure waste of time: the time spent on doing that could've been spent working on features, fixing bugs, level design, and so on.
If you factor in the opportunity cost, premature optimization has a large negative impact on the project.
Finally, when you spend a lot of time on a feature, you will likely get emotionally attached to it. When you realize that it was a waste of time, it can be very frustrating and demoralizing; or it can make you waste even more time trying beyond hope to make the feature work, just because deleting thousands of lines of code is hard.
Remember:
Premature optimization is the root of all evil -- Donald Knuth