Boudewijn said:
In other words: it depends. It depends on the chance of an exception occuring
and the performance difference between the approaches.
The `if' will probably turn into just a few instructions
once the JIT gets through with it -- ten instructions seems
high, but let's just suppose it's ten. We're working on the
back of the envelope here, okay?
Creating and catching the exception will take a variable
amount of work depending on how deep the stack happens to be,
but let's be optimistic and suppose it takes only ten thousand
instructions, including the eventual cost of garbage collecting
the NullPointerException object after it's been discarded.
Under these suppositions, one exception carries the time
penalty of a thousand `if' tests. Using an exception to avoid
the `if' would be a win if the reference is null less than one
thousandth of the time, non-null more than 99.9% of the time.
How much of a gain can you get? Let's suppose the reference
is null just one ten-thousandth of the time, one tenth of the
break-even point. If the code executes a million times, you'll
throw one hundred exceptions at a (supposed) cost of one million
instructions. Meanwhile, you've avoided (supposedly) ten million
instructions for the `if' tests you didn't make. The gain is
nine million instructions, which sounds pretty good.
But how good is it, really? Well, processors vary and
caches vary and memory speeds vary and blah blah blah, but
let's be pessimistic and assume you can execute instructions
at a rate of only 1GHz. You have saved nine milliseconds.
Nine whole milliseconds.
nine
thousandths
of
one
second
You have klutzed up your code, and even under the most
optimistic assumptions imaginable a million executions of
the "optimized" version have saved you
nine
thousandths
of
one
second
That's roughly the amount of time between successive
wave crests of the note on the bottom line of the bass clef,
two octaves below concert A.
nine
thousandths
of
one
second
It's about two-thirds the time of one CRT refresh.
nine
thousandths
of
one
second
It's enough time for a race car going 200 miles/hour
to travel thirty-two inches.
nine
thousandths
of
one
second
Let me ask you this: What are you going to do with all
that extra time? Won't it hang heavy on your hands?