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

前端 未结 8 1827
无人及你
无人及你 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:49

    Here is the compiler (GCC 4.6) generated optimized -O3 code for both options:

    int i = 34567;
    int opt1 = i++ & 1;
    int opt2 = i % 2;
    

    Generated code for opt1:

    l     %r1,520(%r11)
    nilf  %r1,1
    st    %r1,516(%r11)
    asi   520(%r11),1
    

    Generated code for opt2:

    l     %r1,520(%r11)
    nilf  %r1,2147483649
    ltr   %r1,%r1
    jhe  .L14
    ahi   %r1,-1
    oilf  %r1,4294967294
    ahi   %r1,1
    .L14: st %r1,512(%r11)
    

    So 4 extra instructions...which are nothing for a prod environment. This would be a premature optimization and just introduce complexity

提交回复
热议问题