在 Java 中移位是否比乘法和除法更快?.网? [英] Is shifting bits faster than multiplying and dividing in Java? .NET?

查看:48
本文介绍了在 Java 中移位是否比乘法和除法更快?.网?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您碰巧使用 2 的幂,那么在大多数甚至所有 CPU 上左右移动位显然比乘法和除法运算快.但是,它会降低某些读者和某些算法的代码清晰度.移位对于性能是否真的必要,或者我是否可以期望编译器或 VM 注意到这种情况并对其进行优化(特别是当 2 的幂是文字时)?我主要对 Java 和 .NET 行为感兴趣,但也欢迎深入了解其他语言实现.

Shifting bits left and right is apparently faster than multiplication and division operations on most, maybe even all, CPUs if you happen to be using a power of 2. However, it can reduce the clarity of code for some readers and some algorithms. Is bit-shifting really necessary for performance, or can I expect the compiler or VM to notice the case and optimize it (in particular, when the power-of-2 is a literal)? I am mainly interested in the Java and .NET behavior but welcome insights into other language implementations as well.

推荐答案

今天的大多数编译器所做的不仅仅是将乘法或除以二的幂转换为移位运算.在优化时,许多编译器可以使用编译时间常数优化乘法或除法,即使它不是 2 的幂.通常乘法或除法可以分解为一系列移位和加法,如果这一系列操作会更快比乘法或除法,编译器会使用它.

Most compilers today will do more than convert multiply or divide by a power-of-two to shift operations. When optimizing, many compilers can optimize a multiply or divide with a compile time constant even if it's not a power of 2. Often a multiply or divide can be decomposed to a series of shifts and adds, and if that series of operations will be faster than the multiply or divide, the compiler will use it.

对于除以常数,编译器通常可以将运算转换为乘以幻数",然后进行移位.这可能是一个主要的时钟周期节省器,因为乘法通常比除法运算快得多.

For division by a constant, the compiler can often convert the operation to a multiply by a 'magic number' followed by a shift. This can be a major clock-cycle saver since multiplication is often much faster than a division operation.

Henry Warren 的书 Hacker's Delight,关于这个主题的大量信息,在配套网站上也有很好的介绍:

Henry Warren's book, Hacker's Delight, has a wealth of information on this topic, which is also covered quite well on the companion website:

另见讨论(带有一两个链接):

See also a discussion (with a link or two ) in:

无论如何,这一切都归结为允许编译器处理微优化的繁琐细节.多年以来,您自己的转变比编译器更聪明.

Anyway, all this boils down to allowing the compiler to take care of the tedious details of micro-optimizations. It's been years since doing your own shifts outsmarted the compiler.

这篇关于在 Java 中移位是否比乘法和除法更快?.网?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆