什么情况下最好使用无条件 AND (& 而不是 &&) [英] What are the cases in which it is better to use unconditional AND (& instead of &&)

查看:25
本文介绍了什么情况下最好使用无条件 AND (& 而不是 &&)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 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 最终结果无论如何都会在分支中使用,但是 if (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 (&amp; 而不是 &amp;&amp;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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