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

前端 未结 8 1813
无人及你
无人及你 2020-12-01 04:15

Does using bitwise operations in normal flow or conditional statements like for, if, and so on increase overall performance and would it be better

8条回答
  •  时光取名叫无心
    2020-12-01 04:47

    Always these answers about how clever compilers are, that people should not even think about the performance of their code, that they should not dare to question Her Cleverness The Compiler, that bla bla bla… and the result is that people get convinced that every time they use % [SOME POWER OF TWO] the compiler magically converts their code into & ([SOME POWER OF TWO] - 1). This is simply not true. If a shared library has this function:

    int modulus (int a, int b) {
        return a % b;
    }
    

    and a program launches modulus(135, 16), nowhere in the compiled code there will be any trace of bitwise magic. The reason? The compiler is clever, but it did not have a crystal ball when it compiled the library. It sees a generic modulus calculation with no information whatsoever about the fact that only powers of two will be involved and it leaves it as such.

    But you can know if only powers of two will be passed to a function. And if that is the case, the only way to optimize your code is to rewrite your function as

    unsigned int modulus_2 (unsigned int a, unsigned int b) {
        return a & (b - 1);
    }
    

    The compiler cannot do that for you.

提交回复
热议问题