Why was & used over && in java when comparing two bools?

I was looking at the code in Guava https://github.com/google/guava and I see a lot of cool optimizations.

I was curious to use and use && this optimization, and if so, why? Could this be a style choice?

We square int b in IntMath .checkedPow. We want to check that b * b is not overflowing:

checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT); b *= b; 

In this example, why was & & used?

Edit: Matt is right. I compiled this Java code in Java 8:

 public static boolean and (boolean a, boolean b){ return a && b; } public static boolean andBit (boolean a, boolean b){ return a & b; } 

I looked at the byte code using Intellij. I see that we use branching in the "and" functions because we have IFEQ and GOTO.

  // access flags 0x9 public static and(ZZ)Z L0 LINENUMBER 8 L0 ILOAD 0 IFEQ L1 ILOAD 1 IFEQ L1 ICONST_1 GOTO L2 L1 FRAME SAME ICONST_0 L2 FRAME SAME1 I IRETURN L3 LOCALVARIABLE a Z L0 L3 0 LOCALVARIABLE b Z L0 L3 1 MAXSTACK = 1 MAXLOCALS = 2 // access flags 0x9 public static andBit(ZZ)Z L0 LINENUMBER 12 L0 ILOAD 0 ILOAD 1 IAND IRETURN L1 LOCALVARIABLE a Z L0 L1 0 LOCALVARIABLE b Z L0 L1 1 MAXSTACK = 2 MAXLOCALS = 2 } 

To answer the question and faster if the cost of computing an extra <= is faster than branching.

Erwin's comment made me take a closer look at the actual cycle. b * = b is in a while loop, which can repeat a lot. However, b can only be negative in the first cycle, because when we go through b * = b: b will be positive from that moment.

+8
java optimization guava
source share
1 answer

Since conditional branches are somewhat expensive, but comparing values โ€‹โ€‹of integers is very fast, the fastest way to implement this expression in machine instructions will evaluate both subexpressions and will not include a conditional branch.

The way it is written in your code snippet reflects the best way to implement it. Usually we expect the compiler to compose such things on its own, but maybe they tested and found that it wasnโ€™t ...

Or maybe the developer just wrote it faster, because the alternative would be to write it in a way that can be slower - and, of course, there is no good reason for that!

+5
source share

All Articles