Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 723
Luigi Massa Gallerano Avatar asked Jul 10 '12 11:07

Luigi Massa Gallerano


2 Answers

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

like image 116
Louis Wasserman Avatar answered Sep 23 '22 00:09

Louis Wasserman


The only difference is that && and || stop the evaluation as soon as it is known. So for example:

if (a != null && a.get() != null) 

works well with &&, but with & you could get a NullPointerException if a is null.

The only case I can think about where you want to use & is if the second operand has a side effect, for example (probably not the best example but you get the point):

public static void main(String[] args) {     int i = 1;     if (i == 0 & ++i != 2) {     }     System.out.println(i); //2     i = 1;     if (i == 0 && ++i != 2) {     }     System.out.println(i); //1 } 

However, this looks like smelly code to me (in both cases).

like image 26
assylias Avatar answered Sep 20 '22 00:09

assylias