Patrick LAM wrote:
> 
> Catching exceptions is extremely slow, as is anything in general which has
> to do with exceptions. I would say that the second idiom should always be
> favoured.

It depends - suppose catching an exception is 100 times slower than
doing a comparision to null. And then suppose that you hardly ever
expect the value to be null - only, say, 1 in 1000 times. So we have:

Time for if (!null) = t
Time for exception catch = 100t

Time for 1000 invocations with !null = 1000t
Time for 1000 invocations with exception caught once = 100t

So using the exception is 10x faster.

The other reason you might do this is if the not-null case is in a
speed-critical section, and the null case is not.

These cases are certainly rare, and probably in the vast majority of
cases you want to be using if. But I'm sure they come up once in a
while...

Stuart.

PS I don't know whether 100 is the right order of magnitude for catching
an exception. You'll have to benchmark it before making any decisions
based on this analysis.

Reply via email to