Should I bit-shift to divide by 2 in Java? [duplic

2020-02-09 01:13发布

Possible Duplicates:
Is shifting bits faster than multiplying and dividing in Java? .NET?
Quick Java Optimization Question

Many years ago in college, I learned that bit-shifting right by one accomplishes the same thing as dividing by two, but is generally significantly faster. I'm not sure how Java has come along in that regards since the 9-10 years ago I learned about that. Does the Java compiler automatically converts a divide-by-two into a bit-shift operation, or should I manually perform the bit-shift operation in the code myself?

4条回答
看我几分像从前
2楼-- · 2020-02-09 01:25

Yes, this is the very first thing that anyone attempting to do compiler optimizations will do (and has done for at least 5 decades), it most certainly is done by the Java JIT compiler, and you'd probably have a very hard time finding any compiler that doesn't do it.

And even if they didn't, it would still be a premature micro-optimization that should be avoided in favor of having the code be clearer.

查看更多
狗以群分
3楼-- · 2020-02-09 01:36

Modern compilers are clever enough to generate the fastest code for divisions by two. They'll do a shift if it is faster. If what you want to achieve is a division by 2, using a division will make your code clearer. And you'll avoid problems when the number to be divided is negative.

查看更多
看我几分像从前
4楼-- · 2020-02-09 01:40

Unless you're working in a shop and a codebase where bit-shifting is common then, IMHO, you're risking obfuscation. Yes, the expressions may be logically equivalent but:

  • A n00b might get confused by the alternate syntax
  • An old guy who hasn't had to do any bit-shifting since college, like myself, might get confused
  • If you bit shift and feel the need to comment on what you just did then you're definitely off. Simple division is self-documenting and would be clear to anyone who's familiar with elementary math
  • You're not going to outsmart a compiler for optimization on something that simple so don't bother trying
  • As good coding practice it's better to make your code simple/vanilla rather than clever(er)

All this is relative and, again, really depends on your shop's standards. If your colleagues love to bit-shift, then by all means go forth and bit-shift.

查看更多
够拽才男人
5楼-- · 2020-02-09 01:41

The division routine for your CPU will handle this. There is no need for you to do it.

This is known as a premature optimization.

查看更多
登录 后发表回答