You are invited to Log in or Register a free Frihost Account!

Premature optimization is evil, or isn't it?

Have you ever heard that premature optimization is the root of all evil? Is this true? No! More correctly is to say that premature optimization is the root of some evil, not all. I mean premature optimization has nothing to do with wars.

So why do we optimize? There can be several reasons.

Why should we not optimize?

I have noticed that running a profiler (like valgrind) on some small potion of code, then try to optimize it and compare can quite entertaining. It is now 2x as fast, Yes! :p But in my real application this code from the start might be used less than 0.1 % of the time so my win was not very big if you just look at the gained execution speed. But if it's fun it's worth it. Maybe not if you are in a company or something but I don't care about companies. Companies are also the root of some evil so I will just ignore them here.

The most time efficient (your time) approach is probably to write something that works and are not stupid slow. When you have something that runs you can run a profiler to see where the bottlenecks are and optimize them if you want.

1 blog comments below

Optimization is an interesting aspect of programming. With the compiler doing much of it, and the enormous number of times something must be run to recover the programming effort spent doing hand-optimizing, it is tempting to avoid the subject altogether.

One of the programming guides I read included some suggestions:

* Do not optimize

but there was an exception:

* (for experts only) Do not optimize yet

That seems to capture the essence of how to keep your priorities right when programming. Keeping programs straightforward and simple to understand pays huge dividends. Finding a better algorithm is oodles better than fiddling with the code, and usually easier. A professional programmer does need to know the tradeoffs between different details though, so knowing how to optimize is desirable. Actual effort expended on the nitty-gritty changes, though, should likely be done only after a program is functional and likely to be heavily used. Then it makes sense, provided you limit yourself to those areas where a profiler tells you it is most needed.
SonLight on Thu Apr 22, 2010 4:33 pm

© 2005-2011 Frihost, forums powered by phpBB.