Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
like image 396
DD. Avatar asked Nov 24 '11 10:11

DD.


People also ask

Is try catch slow Java?

A compare test did, result says: performance of try catch throw Exception in . Net is over 10 times slow than in Java.

Does Try Catch affect performance?

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.

Is it good to use try catch in Java?

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.

Is try catch faster than if?

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.


1 Answers

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
like image 200
Bohemian Avatar answered Oct 20 '22 06:10

Bohemian