Premature optimization

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(Added 90/10 law ... correct?)
Line 14: Line 14:
 
[http://en.wikipedia.org/wiki/90/10_law#In_software]
 
[http://en.wikipedia.org/wiki/90/10_law#In_software]
  
Therefore, it doesn't make sense to spend a lot of time optimising code, since the optimisable code base is quite small anyway.
+
Therefore, it doesn't make sense to spend a lot of time optimising code before you know what needs optimising.

Revision as of 02:29, 23 July 2009

Premature optimization refers to trying to make code run faster before having a working system. It is often tempting to, once writing a section of code, spend along time making it run as fast as possible. This sounds like a good thing, but generally, is not. This is because of three reasons:

Optimizing code introduces bugs. When optimizing, often complex code is used in an attempt to "do something smart" and hence save time. This will likely introduce bugs into the code. Refer to do the simplest thing that could possibly work for why complex code is undesirable.

It probably wont speed up the system anyway. Usually, only a very small portion of the code in a system determines it's overall speed. Hours spent optimizing every component in the system will probably have little effect on the overall speed.

The code may need to be changed later. As the system takes shape, the requirements may change. This may require rewriting the optimized code, which will a) be harder to do because it is probably complex, and b) mean that you've wasted time optimizing the code in the first place.

The best approach is to keep it simple and get the application into a working state before doing any optimization. Once the application is working, profile it to see were most of the time is being spent, then optimize only that bit. This means that for a minimal optimizing effort, you will get maximum results.

90/10 Law

"90% of the execution time of a computer program is spent executing 10% of the code." [1] [2]

Therefore, it doesn't make sense to spend a lot of time optimising code before you know what needs optimising.

Personal tools