Try catch performance Java

How long (in nanoseconds) does it take to try catch exceptions instead of checking (assuming that the message has HashMap type lookup performance)?

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 );

Solution

In short, inspection is faster You should use a check because:

>Exceptions are expensive! You must create a stack trace (if used, such as records, etc.) and handle special flow control > exceptions should not be used for flow control - exceptions are "special cases" > exceptions are the words of code "I can't handle this situation, I gave up... You handle it!", But here you can deal with it... So deal with it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>