Premature optimization is the root of all evil.
- Tony Hoare
- Tony Hoare
Speculative optimization is always wasted time. In the absence of an actual performance problem, you're just burning time that could be better spent on refactoring your code to make it clearer. This is exacerbated because performance-optimized code is usually harder to read than code which hasn't received such treatment.
Here is what you're doing when you optimize:
- Adding code that now must be maintained.
- Obfuscating the existing code.
- Spending time writing code that doesn't add value.
For example, some people think that having a large number of classes is slower than the alternative. This was (maybe) true a long time ago, but isn't now.
Why? Because the JIT compiler inlines methods automatically. It does a host of other optimizations adaptively (i.e., it decides where the program is spending most of it's time & optimizes those methods & loops).
So, when should you performance-optimize your code? When you have a real performance problem, and a profiler (or similar tool) has identified the place in the code where it occurs.