Re: Speed of comparison to null
kompot@gmail.com wrote:
Hello everyone!
I was told something interesting today:
it is faster to compare a null to a string than a string to null...
Is this true?
I was told that this a new J2EE guideline to use...
So instead of
is (string != null)
do this
if (null != string)
Does this make sense?
Is this true?
The definition of the Java language doesn't say much about
speed, so most questions of faster/slower can only be answered
by referring to a particular JVM implementation. Even then, you
may get wildly different answers depending on whether or not the
code in question has been JITted.
For what it's worth, the first form compiles to a slightly
shorter bytecode sequence than the second, using the ifnonnull
opcode instead of loading an actual null value and comparing to
it. Potentially, then, the first form might be faster -- but
once the JIT runs all bets are off.
Whenever you're considering a micro-optimization of this sort,
it's a good idea to estimate the potential savings in relation to
all the other things your code will be doing. "Take care of the
pennies and the pounds will take care of themselves," sure, but
we're probably talking about micropennies and megapounds.
--
Eric Sosman
esosman@acm-dot-org.invalid