What are the cases in which it is better to use unconditional AND (& instead of &&)

后端 未结 11 709
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 10:33

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 (&

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 10:44

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

    (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.)

提交回复
热议问题