Optimize – but only when you have a real need
A common habit amongst us software developers is the practice of sub optimization. If you find yourself thinking “I might use this function/class later, I’d better make it general,” or “I’ll use a static variable since it’s faster” then you are guilty of sub optimizing.
Optimizing prematurely is bad, and usually get you into trouble. It tends to make your code unnecessarily complex and difficult to maintain. A much better practice is what the agile methods, like Extreme Programming, recommend.
- Write a unit test.
- Start with the simplest possible implementation to make your test pass.
- Refactor the code for the purpose of making it easier to maintain, fulfilling the principle of DRY (Don’t Repeat Yourself). The unit test is your insurance that the functionality of the code is unchanged.
If you follow these simple rules, and leave the optimizations until you really need them you will avoid spending time optimizing things that doesn’t need to be optimized (what’s a couple of milliseconds in a process that take several seconds?) You’ll also gain simpler, more readable code and spend less time maintaining it.