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 );
A compare test did, result says: performance of try catch throw Exception in . Net is over 10 times slow than in Java.
In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.
Java try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.
In short, the check is way faster. You should use the check because:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With