How is the modulo operator implemented in the HotSpot JVM?

后端 未结 3 1469
醉话见心
醉话见心 2021-01-22 21:21

I understand that the modulus operation can be optimised using a little & wise magic where the divisor is a power of 2...

  • and presuma
3条回答
  •  时光说笑
    2021-01-22 22:09

    I spent some time on this very question, writing this blog post with all the details.

    In short:

    • The HotSpot JDK 1.8 irem (mod int) is ~20% slower than the n & (pow2-1) trick
    • The HotSpot JDK 1.8 frem (mod float) is 3x slower
    • You mileage varies based on JIT passes, so the benefit for Int's is minimal

    So, there is a clear benefit to not do mod on Doubles, and you might get some benefit with Natural Integer Dividends and power of 2 Divisors.

提交回复
热议问题