我应该在 Java 中进行位移除以 2 吗?
许多年前,在大学里,我了解到位移位右移一位可以实现与除以二相同,但通常要快得多。我不确定自从 9 到 10 年前我了解 Java 以来,Java 在这方面是如何发展的。 Java编译器是否会自动将除以二转换为位移操作,还是我应该自己在代码中手动执行位移操作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
恕我直言,除非您在位移位很常见的商店和代码库中工作,否则您将面临混淆的风险。是的,这些表达式在逻辑上可能是等价的,但是:
所有这些都是相对的,而且,实际上取决于您商店的标准。如果你的同事喜欢进行位移,那么一定要继续进行位移。
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:
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 年),它肯定是由 Java JIT 编译器完成的,并且您可能很难找到任何不这样做的编译器。
即使他们不这样做,这仍然是一种不成熟的微优化,应该避免这种优化,以便让代码更清晰。
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.
CPU 的除法例程将处理这个问题。你没有必要这样做。
这称为过早优化。
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.