Does Java optimize division by powers of two to bitshifting?

前端 未结 3 1954
抹茶落季
抹茶落季 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 01:58

    While the accepted answer is right in the sense that the division can't be simply replaced by a right shift, the benchmark is terribly wrong. Any Java benchmark running for less than one second is probably measuring the interpreter's performance - not something you usually care about.

    I couldn't resist and wrote an own benchmark which mainly shows that it's all more complicated. I'm not trying to fully explain the results, but I can say that

    • a general division is a damn slow operation
    • it gets avoided is much as possible
    • division by a constant gets AFAIK always somehow optimized
    • division by a power of two gets replaced by a right shift and an adjustment for negative numbers
    • a manually optimized expression might be better

提交回复
热议问题