Performance wise, how fast are Bitwise Operators vs. Normal Modulus?

Maven picture Maven · Dec 5, 2013 · Viewed 30.6k times · Source

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) {

}

Answer

Jerry Coffin picture Jerry Coffin · Dec 5, 2013

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.