Does Java optimize division by powers of two to bitshifting?

前端 未结 3 1947
抹茶落季
抹茶落季 2020-12-18 01:43

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 follow

3条回答
  •  暖寄归人
    2020-12-18 02:19

    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

提交回复
热议问题