3

我已经看到多个来源(一些在这里,以及关于按位运算的维基百科文章)说使用位移来计算比正常的乘法/除法/加法更快。但是,他们还提到,这仅适用于较旧的处理器,并且大多数现代处理器已经做到了,因此速度几乎相等。

该声明的有效性如何?在 Java 或 C# 中仅使用常规数学操作数是否安全?真的有必要使用位移来代替那些操作数吗?

4

2 回答 2

9

You just leave this to the compiler. Good compilers know about the hardware that they are targetting. If the compiler knows that bitwise operations are faster, then it can emit code to do it that way. You should always write the human readable code in the most clear fashion, the fashion that correctly expresses the operation being performed. Let the compiler do the rest.

As for whether or not it is still true that bitwise operations can be faster than arithmetic, I believe that they are. Certainly many modern C++ compilers will emit code that uses bitwise operations for arithmetic.

于 2012-05-22T15:18:36.210 回答
2

我不确定在当今的体系结构和编译器上使用按位运算和使用简单运算符之间的差异有多大(我的猜测是......在大多数问题上几乎没有)。

我的直觉是,您现在编写的大多数代码实际上并不是 CPU 操作的瓶颈,而是数据库访问、I/O、网络(是的,我在这里是多余的)。

例如,JVM 的编译器已经针对运行代码的架构优化了许多操作,将这种必要性从开发人员那里抽象出来(这就是它的用途)。

我想说的最后一点是……可读性很重要。不管一些按位运算爱好者会争论什么,大多数开发人员通常在代码中间的按位运算的可读性要差得多,而不是简单地使用标准数学。

理解代码的成本以及在需要更改代码时引入错误的可能性增加,恕我直言,风险远远超过收益。编写高效的代码很重要,但它仍然必须是人类可读的。

免责声明:在某些领域,数学运算的数量可能会成为一个因素,但这肯定不是常态。

于 2012-05-22T15:23:18.663 回答