When should you optimize your code?

Once new developers get beyond the basics, there is a tendency to start looking for ‘clever’ solutions to problems, or worrying about whether solution A is faster than solution B.

Unless you know you have a performance problem with a solution now, or have a design constraint where you know you need to account for a performance goal and ensure your approach will meet that goal, then you’re worry about problems you don’t have.

Spend time worrying about whether your code is easily to read and understand. Worry about performance problems when you understand what performance problem you have.

Donald Knuth is famously quoted as saying “premature optimization is the root of all evil” – meaning, don’t spend time optimizing for problems you don’t have. In his paper “Structured Programming with goto Statements”, the full quote where this well known expression originated has more context:

“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%”

When you know you have performance issues then spend time to address them, otherwise, focus on making sure your solution works, and that your code is easy to maintain in the future.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.