Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

optimization - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...