0

I usually use n(a number) % 2 to check whether it is a even or odd. Recently, I just discovered another way by using bit wise.

if(n&1)
   cout<<"Odd";
else
   cout<<"Even";

Is it faster than the other? Should I use it? Thank you!

Nhân Nguyễn
  • 105
  • 1
  • 4
  • 9
  • 4
    `is it faster than the other? `: Have you committed any benchmarks? – 101010 Jun 01 '16 at 08:56
  • 3
    n&1 should be faster since it checks if the first bit in the number bitstring is setted on or off, the '%' operator has to calculate the rest. – PRDeving Jun 01 '16 at 08:59
  • 1
    Leaving how compiler acts at this situation, n%2 would require a multiplication and a subtraction operation which are costly operations. On the other hand, & is just a single and simple operation. – awatan Jun 01 '16 at 09:00
  • 2
    @PRDeving Wrong. Please don't post answers in comments, place them in the answer box, so that they can be downvoted as appropriate. –  Jun 01 '16 at 09:00
  • A half-decent compiler will implement `% 2` with `& 1` if it's faster. Stick with the readable one, inspect the generated code if you're worried. (There isn't a one-to-one correspondence between C++ code and the instructions generated by the compiler.) – molbdnilo Jun 01 '16 at 09:03
  • I don't think it should use &1 instead of %2, as I think using a less common approach is a potentially maintain nightmare – ggrr Jun 01 '16 at 09:05
  • @hvd u are wrong, there's a little difference when using tons of iterations https://jsfiddle.net/9bpzx7yu/ (you will have to open the console to see the msgs and wait, 100.000.000 iterations takes time) – PRDeving Jun 01 '16 at 09:15
  • 1
    It doesn't matter, so long as you are using an *unsigned* integer. With a signed integer, you will definitely see differences in the assembly output (at least on MSVC, where using `n % 2` when `n` is a signed integer will result in ugly, slow, branching code). – Cody Gray - on strike Jun 01 '16 at 09:20
  • @PRDeving This question isn't about JavaScript, it's about C++. I have no clue which optimisations are common in JavaScript interpreters, but I do know enough about C++ compilers. –  Jun 01 '16 at 09:21
  • @hvd indeed, i do, i know both JS and C, and in C the performance impact is even higher, thanks god i can show it to you here :) https://ideone.com/49jNC9 – PRDeving Jun 01 '16 at 09:47
  • @PRDeving I couldn't reproduce your result (tried running it several times) – anatolyg Jun 01 '16 at 09:56
  • @anatolyg no problem pal, here's another online compiler that shows the same performance difference http://cpp.sh/7xea – PRDeving Jun 01 '16 at 10:08
  • 1
    @PRDeving That's a bad test. You're including the time needed for printing of BM1 in the time for BM2. You're not doing nearly enough work not to let initialisation time become significant. There may be other problems. Swap BM1 and BM2 and suddenly BM2 will be faster. –  Jun 01 '16 at 10:09

1 Answers1

6

The compiler could very easily optimize either operation into the faster one, so in practice it probably makes little difference.

I ran this experiment with my gcc compiler (5.3 on ubuntu). Given this code:

#include <iostream>

int main()
{

    for(int i=0; i<100; ++i) {
        //if(i % 2 == 0)
        if(!(i & 1)) 
            std::cout << "i is odd" << std::endl;
        else
            std::cout << "i is even" << std::endl;
    }   
}

Whichever of the if lines I commented out, the assembly code produced is exactly the same, namely:

mov eax, DWORD PTR [rbp-4]  # D.35290, i
and eax, 1  # D.35290,
test    eax, eax    # D.35290

In other words the compiler produced the AND version of the comparison in both cases. This is with default optimisation.

Smeeheey
  • 9,906
  • 23
  • 39
  • Which one should I use ? – Nhân Nguyễn Jun 01 '16 at 09:01
  • 1
    As per above edit, it makes no difference. Use either one. The compiler will choose the AND option because I guess it thinks its faster – Smeeheey Jun 01 '16 at 09:07
  • @NhânNguyễn Use the most explicit and most used of form => `%2`. In a general way, always write what you want to do, not a trick which seams doing what you need but shortcut compiler optimization. Also tricks are often not portable nor maintenaible – Garf365 Jun 01 '16 at 09:15