Reputation: 21991
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
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
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
Reputation: 425063
In short, the check is way faster. You should use the check because:
Upvotes: 25
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