When is it better to use unconditional AND (& instead of &&)

I would like to know some cases in Java (or, more broadly: in programming), when in Boolean expressions it is preferable to use the unconditional AND ( & ) instead of the conditional version ( && ).

I know how they work, but I can’t think of a case when you should use one & .

+48
java optimization
Jul 10 2018-12-12T00:
source share
11 answers

I found cases in real life where both sides of the expression were really cheap, so he shaved a nanosecond or two to avoid the branch and use unconditional & instead of && . (These were extremely high-performance math utilities, though, I would almost never use it in other code, and I would not do it anyway without exhaustive benchmarking to prove that it is better.)

(To give concrete examples, x > 0 will be super cheap and without side effects. Why risk a misprediction of the branch to avoid a test that will be so cheap? Of course, since this is a boolean final result will still be used in the branch, but if (x >= 0 && x <= 10) includes two branches, and if (x >= 0 & x <= 10) includes only one.)

+60
Jul 10 '12 at 11:15
source share

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

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

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

The only time I can think about where you want to use & is, for example, if the second operand has a side effect (maybe 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).

+20
Jul 10 '12 at 11:10
source share

& & allows jvm to perform a short circuit assessment. That is, if the first argument is false, then it does not need to check the second argument.

One and will run both sides independently.

So, as a far-fetched example, you might have:

 if (account.isAllowed() & logAccountAndCheckFlag(account)) // Do something 

In this example, you can always register the fact that the account holder has tried to do something.

I do not think that I have ever used one in commercial programming.

+14
Jul 10 '12 at 11:11
source share

Wikipedia has well described short circuit assessment

Where do you prefer short-circuit operators?

From the same link:

  • Failure to fulfill the second condition leads to an ineffective side effect
  • Code performance

A short circuit can lead to errors in branch prediction on modern processors and significantly reduce performance (a notable example is a highly optimized beam with the intersection code with the axis aligned in the beam tracking) [clarification needed]. Some compilers can detect such cases and emit faster code, but this is not always possible due to a possible violation of the C standard. Highly optimized code should use other methods for this (for example, using assembly code manually)

+11
Jul 10 '12 at 11:23
source share

If there are side effects that should happen, but it's a little ugly.

Bitwise AND ( & ) is mostly useful just for this - bitwise math.

+7
Jul 10 '12 at 11:13
source share

Checking input is one of the possible cases. Usually you want to report all errors in the form to the user in one pass, and not stop after the first and force them to click the button again and get only one error each time:

 public boolean validateField(string userInput, string paramName) { bool valid; //do validation if (valid) { //updates UI to remove error indicator (if present) reportValid(paramName); } else { //updates UI to indicate a problem (color change, error icon, etc) reportInvalid(paramName); } } public boolean validateAllInput(...) { boolean valid = true; valid = valid & validateField(userInput1, paramName1); valid = valid & validateField(userInput2, paramName2); valid = valid & validateField(userInput3, paramName3); valid = valid & validateField(userInput4, paramName4); valid = valid & validateField(userInput5, paramName5); return valid; } public void onSubmit() { if (validateAllInput(...)) { //go to next page of wizard, update database, etc processUserInput(userInput1, userInput2, ... ); } } public void onInput1Changed() { validateField(input1.Text, paramName1); } public void onInput2Changed() { validateField(input2.Text, paramName2); } ... 

Of course, you could trivially avoid the need to evaluate the short circuit in validateAllInput() by refactoring the logic if (valid) { reportValid() ... outside validateField() ; but then you will need to call the extracted code every time validateField () is called; with a minimum of 10 extra lines for method calls. As always, this is the case when compromise is best for you.

+7
Jul 10 2018-12-12T00:
source share

If the expression is trivial, you can get micro-optimization with & or | in that you prevent the branch. i.e.

 if(a && b) { } if(!(a || b)) { } 

coincides with

 if (a) if (b) { } if (!a) if (!b) { } 

which has two places that branches can have.

However, using unconditional & or | , there can only be one branch.

It helps or doesn't really depend on what the code does.

If you use this, I am sugegst commenting on it so that it makes it clear why this was done.

+6
Jul 10 2018-12-12T00:
source share

There is no specific use for solitary, but you can consider the following situation.

 if (x > 0 & someMethod(...)) { // code... } 

Note that someMethod() performs some operation that will modify instance variables or do something that will affect behavior later in processing.

So, in this case, if you use the && operator and the first condition is not met, it will never go into someMethod() . In this case, one operator & is sufficient.

+5
Jul 10 '12 at 11:14
source share

Since & is a bit-wise statement, you can perform up to 32 checks in one operation at a time. This can be a significant increase in speed for these specific use cases. If you need to check a large number of conditions and do it often, and the cost of boxing / unpacking conditions is amortized by the number of checks or if you save data on disk and in RAM in this format (this is a more efficient space for storing 32 conditions in one bit mask), the operator & can get huge speed benefits compared to 32 individual && . For example, if you want to select all units that can be moved, this is infantry, there is a weapon update and is controlled by player 3, you can do:

 int MASK = CAN_MOVE | INFANTRY | CAN_ATTACK | HAS_WEAPON_UPGRADE | PLAYER_3; for (Unit u in allunits) { if (u.mask & MASK == MASK) { ...; } } 

See my other answers on the relevant question for more information on this topic.

+3
Jul 11 '12 at 3:11
source share

The only thing I can think of is when you need to call a method or execute code, regardless of whether the first expression evaluates to true or false :

 public boolean update() { // do whatever you want here return true; } // ... if(x == y & update()){ /* ... */} 

Although you can do it without & :

 if(x == y){/* ... */} update(); 
+1
Jul 10 '12 at 11:14
source share

A short circuit can lead to errors in branch prediction on modern processors and significantly reduce performance (a notable example is a highly optimized beam with the axis intersection code with a rectangular field in ray tracing) [clarification needed].

+1
Jul 25 '12 at 8:24
source share



All Articles