在性能方面,按位运算符与标准模数有多快? [英] Performance wise, how fast are Bitwise Operators vs. Normal Modulus?
问题描述
在普通流或诸如for
,if
之类的条件语句中使用按位运算会提高整体性能,并且在可能的情况下使用它们会更好吗?例如:
Does using bitwise operations in normal flow or conditional statements like for
, if
, and so on increase overall performance and would it be better to use them where possible? For example:
if(i++ & 1) {
}
vs.
if(i % 2) {
}
推荐答案
除非您使用的是古老的编译器,否则它已经可以自行处理此级别的转换.也就是说,现代编译器可以并且将使用按位AND
指令来实现i % 2
,前提是可以在目标CPU上这样做(公平地说,通常会这样做).
Unless you're using an ancient compiler, it can already handle this level of conversion on its own. That is to say, a modern compiler can and will implement i % 2
using a bitwise AND
instruction, provided it makes sense to do so on the target CPU (which, in fairness, it usually will).
换句话说,至少在使用具有合理能力的优化程序的现代编译器的情况下,不要期望它们之间在性能上有任何差异.在这种情况下,合理地"也有相当宽泛的定义-即使几十年前的相当多的编译器也可以毫不费力地处理这种微优化.
In other words, don't expect to see any difference in performance between these, at least with a reasonably modern compiler with a reasonably competent optimizer. In this case, "reasonably" has a pretty broad definition too--even quite a few compilers that are decades old can handle this sort of micro-optimization with no difficulty at all.
这篇关于在性能方面,按位运算符与标准模数有多快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!