gpt4 book ai didi

java - Java 6 中 if/or 与 try/catch 的复合成本

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:03 25 4
gpt4 key购买 nike

我们目前有以下复合 if 语句...

if ((billingRemoteService == null)
|| billingRemoteService.getServiceHeader() == null
|| !"00".equals(billingRemoteService.getServiceHeader().getStatusCode())
|| (billingRemoteService.getServiceBody() == null)
|| (billingRemoteService.getServiceBody().getServiceResponse() == null)
|| (billingRemoteService.getServiceBody().getServiceResponse().getCustomersList() == null)
|| (billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList() == null)
|| (billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList().get(0) == null)
|| (billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList().get(0).getBillAccountInfo() == null)
|| (billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList().get(0).getBillAccountInfo().getEcpdId() == null)) {
throw new WebservicesException("Failed to get information for Account Number " + accountNo);
}

return billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList().get(0);

这不能简化为...
try {
//Check to be sure there is an EpcdId.
(billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList().get(0).getBillAccountInfo().getEcpdId();
return billingRemoteService.getServiceBody().getServiceResponse().getCustomersList().getCustomersList().get(0);
} catch (NullPointerException npe) {
throw new WebservicesException("Failed to get information for Account Number " + accountNo);
}

如果是这样,Java 6 下两种方法之间的“成本”差异是什么?这似乎是一个非常复杂的 if 语句,只是为了验证所有中间调用都不为空。对于不同的帐户,多次调用此操作。

最佳答案

我必须不同意埃德温巴克的论点。

他说:

As others have stated, exceptions are more expensive than if statements. However, there is an excellent reason not to use them in your case. "Exceptions are for exceptional events"

When unpacking a message, something not being in the message is expected error checking, not an exceptional event.



这实质上是说,如果您进行错误检查,则预期会出现错误(因为您正在寻找它),因此并不异常(exception)。

但这不是“特殊事件”的意思。异常事件是指不寻常/不寻常/不太可能发生的事件。异常(exception)是关于事件发生的可能性,而不是关于您是否(或应该)期待和/或寻找它。

因此,回到首要原则,避免异常的根本原因是成本权衡:显式测试事件的成本与抛出、捕获和处理异常的成本。准确地说。

If the probability of the event is P

  • the average cost of using exceptions is:

    P * cost of an exception being created/thrown/caught/handled + (1 - P) * cost of no explicit tests

  • the average cost of not using exceptions is:

    P * cost testing for the condition when it occurs and doing the error handling + (1 - P) * cost of testing when the condition doesn't occur.



当然,这就是“异常”==“不太可能”的用武之地。因为,如果 P 越接近 0,使用异常的开销就会变得越来越小。如果 P 足够小(取决于问题),异常将更有效。

因此,在回答最初的问题时,不仅仅是 if/else 与异常的成本。您还需要考虑您正在测试的事件(错误)的可能性。

另一件需要注意的事情是 JIT 编译器有很大的空间来优化这两个版本。
  • 在第一个版本中,可能会有很多重复的子表达式计算,以及重复的幕后空检查。 JIT 编译器可能能够优化其中的一些,尽管这取决于是否存在副作用。如果不能,那么测试序列可能会相当昂贵。
  • 在第二个版本中,JIT 编译器可以在不使用异常对象的情况下注意到在同一方法中抛出和捕获异常的范围。由于异常对象不会“转义”它可以(理论上)被优化掉。如果发生这种情况,使用异常的开销将几乎消失。


  • (这是一个有效的例子,可以清楚地说明我的非正式方程的含义:
      // Version 1
    if (someTest()) {
    doIt();
    } else {
    recover();
    }

    // Version 2
    try {
    doIt();
    } catch (SomeException ex) {
    recover();
    }

    和以前一样,让 P 是 概率甚至会发生导致异常的情况。

    版本 #1 - 如果我们假设成本是 someTest()测试成功还是失败都一样,用“doIt-success”表示没有异常抛出时doIt的代价,则 平均 一次执行版本 #1 的成本是:
      V1 = cost("someTest") + P * cost("recover") + (1 - P) * cost("doIt-success")

    版本 #2 - 如果我们假设成本是 doIt()是否抛出异常都是一样的,那么 平均一次执行版本 #2 的成本是:
      v2 = P * ( cost("doit-fail") + cost("throw/catch") + cost("recover") ) +
    (1 - P) * cost("doIt-success")

    我们从另一个中减去一个以给出 的差异平均成本。
      V1 - V2 = cost("someTest") + P * cost("recover") + 
    (1 - P) * cost("doIt-success") -
    P * cost("doit-fail") - P * cost("throw/catch") -
    P * cost("recover") - (1 - P) * cost("doIt-success")

    = cost("someTest") - P * ( cost("doit-fail") + cost("throw/catch") )

    请注意 recover() 的成本以及费用在哪里 doIt()成功取消。我们剩下一个正分量(进行测试以避免异常的成本)和一个与失败概率成正比的负分量。该等式告诉我们,无论 throw/catch 开销多么昂贵,如果概率 P足够接近于零,差异将为负。

    对此评论的回应:

    The real reason you shouldn't catch unchecked exceptions for flow control is this: what happens if one of the methods you call throws an NPE? You catching the NPE assumes that it came from your code when it may have come from one of the getters. You may be hiding a bug underneath the code and this can lead to massive debugging headaches (personal experience). Performance arguments are useless when you might be hiding bugs in your (or others') code by catching an unchecked exception like NPE or IOOBE for flow control.



    这与埃德温·巴克斯 (Edwin Bucks) 的论点确实相同。

    问题是“流量控制”是什么意思?
  • 一方面,抛出和捕获异常是一种流量控制形式。所以这意味着你永远不应该抛出和捕获未经检查的异常。这显然没有任何意义。
  • 那么我们又回到争论不同类型的流量控制上,这与争论什么是“异常”和什么是“非异常”是一样的。

  • 我认识到您在捕获 NPE 和类似情况时需要小心,以确保您不会捕获来自意外来源(即不同的错误)的 NPE。但在 OP 的示例中,这种情况的风险很小。你可以而且应该检查那些看起来像简单的 getter 的东西真的是简单的 getter。

    而且您还必须认识到,捕获 NPE(在这种情况下)会产生更简单的代码,这可能比 if 中的长条件序列更可靠。陈述。请记住,这种“模式”可以在很多地方复制。

    底线是异常和测试之间的选择可能很复杂。在某些情况下,告诉您始终使用测试的简单口头禅会给您错误的解决方案。并且“错误”可能不太可靠和/或可读性较差和/或代码较慢。

    关于java - Java 6 中 if/or 与 try/catch 的复合成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12358686/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com