Tuesday, November 22, 2016

Do. Not. Optimize.

You've probably heard this quote before:
Premature optimization is the root of all evil.
 - 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.
But what's that you say?  You have the experience and know-how to decide when optimization is needed?  Maybe, but probably not.   The people at Sun and Oracle may or may not be smarter than  you or me, but they certainly know more about optimizing Java bytecode than we do.

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.

Post a Comment