什么情况下最好使用无条件AND(&而不是&&) [英] What are the cases in which it is better to use unconditional AND (& instead of &&)
问题描述
我想知道Java中的一些情况(或更一般地说:编程中的
)当布尔表达式中首选使用无条件 AND
时(&
)而不是条件版本(&&
)。
I'd like to know some cases in Java (or more generally:
in programming) when it is preferred in boolean expressions to use the unconditional AND
(&
) instead of the conditional version (&&
).
我知道它们是如何工作的,但我不能考虑使用单个&
值得的情况。
I know how they work, but I cannot think about a case when use the single &
is worth it.
推荐答案
我在现实生活中找到了表达式两边都非常便宜的案例,所以它削减了一两纳秒以避免分支和使用无条件&
而不是&&
。 (但这些是非常高性能的数学实用程序;我几乎从不在其他代码中使用它,如果没有详尽的基准测试来证明它更好,我也不会这样做。)
I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional &
instead of &&
. (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)
(举个具体的例子, x> 0
将是超级廉价和无副作用。为什么要冒险分支错误预测以避免一个测试会变得如此便宜吗?当然,因为它是一个 boolean
最终结果将在分支中使用,但如果(x> = 0&& x< = 10)
涉及两个分支, if(x> = 0& x< = 10)
只涉及一个。)
(To give specific examples, x > 0
is going to be super cheap and side-effect-free. Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway? Sure, since it's a boolean
the end result is going to be used in a branch anyway, but if (x >= 0 && x <= 10)
involves two branches, and if (x >= 0 & x <= 10)
involves only one.)
这篇关于什么情况下最好使用无条件AND(&而不是&&)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!