DD.
DD.

Reputation: 21991

Try Catch Performance Java

How much longer (in nanoseconds) does a try-catch take when catching an exception rather than doing a check (assuming message has HashMap type performance for lookup)?

    try {
        timestamp = message.getLongField( MessageField.TIMESTAMP );
    } catch (MissingDataException e) {
        //Not all messages contain this field
    }

vs

if (message.contains(MessageField.TIMESTAMP))
    timestamp = message.getLongField( MessageField.TIMESTAMP );

Upvotes: 7

Views: 8917

Answers (4)

alex
alex

Reputation: 5201

Another answer is "Who cares!". It's wrong!

In any case, if you want to benchmark it, use https://github.com/google/caliper

Upvotes: 3

Stephen C
Stephen C

Reputation: 718886

Would like to quantify this...

It is literally impossible to quantify in general. Not in nanoseconds ... because it depends on the execution platform. And not even in percentage terms.

The time depends largely on the time taken to capture the stack trace, and that depends on how deep the stack is when the exception is thrown. And that's just one of the reasons that using Java exceptions instead of regular conditional statements is a really bad idea.

But the flip side is that there is scope for the JIT compiler to heavily optimize exception-related code provided that it can determine that the stack trace for and exception thrown at a particular point is never going to be used.


If you really want some (IMO, pointless and largely meaningless) numbers, you will need to do your own benchmarking. Good luck.

Upvotes: 1

Bohemian
Bohemian

Reputation: 425063

In short, the check is way faster. You should use the check because:

  • Exceptions are EXPENSIVE! A stack trace must be created (if used, eg logged etc) and special flow control handled
  • Exceptions should not be used for flow control - Exceptions are for the "exceptional"
  • Exceptions are the code's way of saying "I can't handle this situation and I'm giving up... you deal with it!", but here you can handle it... so handle it

Upvotes: 25

Mike Q
Mike Q

Reputation: 23229

The answer is "much longer". Exceptions are slow compared to a check due to time to build the stacktrace.

As a general point using exceptions to control program flow is a bad idea as it clutters the code up. Always do the check and leave exceptions for when "exceptional" things happen.

Upvotes: 3

Related Questions