Java Reference
In-Depth Information
Oh Go Ahead, Prematurely Optimize
Donald Knuth is widely credited with coining the term “premature optimization,” which is
often used by developers to claim that the performance of their code doesn't matter, and if it
does matter, we won't know that until the code is run. The full quote, if you've never come
across it, is “We should forget about small efficiencies, say about 97% of the time; premature
optimization is the root of all evil.”
The point of this dictum is that in the end, you should write clean, straightforward code that
is simple to read and understand. In this context, “optimizing” is understood to mean em-
ploying algorithmic and design changes that complicate program structure but provide better
performance. Those kind of optimizations indeed are best left undone until such time as the
profiling of a program shows that there is a large benefit from performing them.
What optimization does not mean in this context, however, is avoiding code constructs that
are known to be bad for performance. Every line of code involves a choice, and if there is a
choice between two simple, straightforward ways of programming, choose the more per-
formant one.
At one level, this is well understood by experienced Java developers (it is an example of their
art, as they have learned it over time). Consider this code:
log . log ( Level . FINE , "I am here, and the value of X is "
+ calcX () + " and Y is " + calcY ());
This code does a string concatenation that is likely unnecessary, since the message won't be
logged unless the logging level is set quite high. If the message isn't printed, then unneces-
sary calls are also made to the calcX() and calcY() methods. Experienced Java developers
will reflexively reject that; some IDEs (such as NetBeans) will even flag the code and sug-
gest it be changed. (Tools aren't perfect, though: NetBeans will flag the string concatenation,
but the suggested improvement retains the unneeded method calls.)
This logging code is better written like this:
iif ( log . isLoggable ( Level . FINE )) {
log . log ( Level . FINE ,
"I am here, and the value of X is {} and Y is {}" ,
new Object []{ calcX (), calcY ()});
Search WWH ::

Custom Search