【问题标题】:Strange implementation of Guava LongMath.checkedAdd [duplicate]Guava LongMath.checkedAdd 的奇怪实现
【发布时间】:2013-08-16 12:52:11
【问题描述】:
public static long checkedAdd(long a, long b) {
    long result = a + b;
    checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0);
    return result;
}

我很感兴趣为什么布尔逻辑 |在这里使用。为什么不使用条件短路||?

【问题讨论】:

  • 你会怎么写?
  • checkNoOverflow((a ^ b) = 0);
  • 出于性能原因想要避免分支的代码中并不少见。

标签: java guava long-integer integer-overflow


【解决方案1】:

该类中的第一条评论:

// NOTE: Whenever both tests are cheap and functional, it's faster to use 
// &, | instead of &&, ||

更多内容:https://stackoverflow.com/a/11412121/869736

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 2011-07-23
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2013-05-28
    • 1970-01-01
    相关资源
    最近更新 更多