尝试Catch Performance Java [英] Try Catch Performance Java

查看:123
本文介绍了尝试Catch Performance Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

捕获异常而不是进行检查时,try-catch需要多长时间(以纳秒为单位)(假设消息具有HashMap类型的查找性能)?

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


推荐答案

简而言之,检查是方式更快。你应该使用支票,因为:

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

这篇关于尝试Catch Performance Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆