1

Which one is the more efficient way to check whether the number is even? Given that num is an int.

if(num % 2 == 0)
// Or
if((num & 1) == 0)
Nekuskus
  • 143
  • 1
  • 11
  • 2
    Careful: you probably mean `(num & 1) == 0`. Lots of duplicates for this one, and the answer depends on the type of `num` and the language – harold Jun 12 '20 at 14:48
  • Thank you for making me notice that! – Nekuskus Jun 12 '20 at 14:50
  • 2
    C# works similar to C in this regard, and [here are some actual results](https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBDAzgWwB8ABAJgEYBYAKGIGYACMhgYQYG8aHunHgIIAGwYBLXDABuMAHYAKAK4jpGBggCUHLj23EA7KoYBSBqQYBeMwwAMAbi3cAvvYbP6DfkNHip00rKUq6prU2jr6CEYm5pa2zk4hPK58AsJikjJ0/sqqGpwJoUz6shEAZAzkGhbWdvkM8Q5AA===), look at the types. – harold Jun 12 '20 at 14:56
  • @Nekuś the `%` is slower than `&`. – Alessio Cantarella Jun 12 '20 at 14:58
  • Thank you @harold! This link is of great help. – Nekuskus Jun 12 '20 at 14:59
  • 1
    This is dependent of, how you define the `num`. If it is unsigned - for the `%`, compiler will just use mask, i.e. performance will be as same as with using `&`. However, if `num` is defined as `int`, i.e. signed int - then compiler will use several assembly commands, to prepare sign of result. Bevause of "-5 % 2 == -1". (my info - for gcc compiler, for C# result can be other). – olegarch Jun 13 '20 at 01:03

0 Answers0