javaoptimizationjavac

Does Java optimize division by powers of two to bitshifting?


Does the Java compiler or the JIT compiler optimize divisions or multiplications by a constant power of two down to bitshifting?

For example, are the following two statements optimized to be the same?

int median = start + (end - start) >>> 1;
int median = start + (end - start) / 2;

(basically this question but for Java)


Solution

  • No, the Java compiler doesn't do that, because it can't be sure on what the sign of (end - start) will be. Why does this matter? Bit shifts on negative integers yield a different result than an ordinary division. Here you can see a demo: this simple test:

    System.out.println((-10) >> 1);  // prints -5
    System.out.println((-11) >> 1);  // prints -6
    System.out.println((-11) / 2);   // prints -5
    

    Also note that I used >> instead of >>>. A >>> is an unsigned bitshift, while >> is signed.

    System.out.println((-10) >>> 1); // prints 2147483643
    

    @Mystical: I wrote a benchmark, that shows that the compiler / JVM doesn't do that optimization: https://ideone.com/aKDShA