0

Lets say I am checking for odd numbers:

(i % 2 == 1)

Will the compiler convert that operation to:

if(a & 1)

?

I am aware that bitwise operations are faster and that sometimes I will work with bits.

However my question is: If the normal arithmetic is more readable (in most instances), when shall I use bitwise if the compiler might convert it later?

Or shall I always use bitwise whenever is posible (even if it is less readable)?

jww
  • 97,681
  • 90
  • 411
  • 885
Juan
  • 31
  • 6
  • 1
    You can be fairly certain the compiler will optimize such trivial stuff for you (as long as you compile with optimizations enabled of course). But, just check the generated asm to make sure. – Jesper Juhl Sep 02 '18 at 13:46
  • Possible duplicate of [What is the fastest way to find if a number is even or odd?](https://stackoverflow.com/q/2229107/608639) – jww Sep 02 '18 at 14:14
  • If your concern is speed then you can write a test function that does one of the alternatives like 100 000 times, time it and then do the same with the other alternatives and compare. Do it with both debug and release versions and you'll be surprised. –  Sep 02 '18 at 14:28
  • By the way `i % 2 == 1` does not work if `i` is signed and can be negative – harold Sep 03 '18 at 00:39

2 Answers2

5

You should always use the form that is better readable by human beings. If execution speed matters you have to profile your program and look at the assembly your compiler generates.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • 2
    +1 And with the magic of modern optimizing compilers, it's very likely that something that is "too clever by half" and something that is "human readable and maintainable" will both compile to the same code. So premature optimization is worth avoiding... PROFILE PROFILE PROFILE is the only way to be sure. I've seen hand-optimized (and largely unreadable) code that became less performant. Because the stupid dev (*ahem*, myself) didn't actually profile the "improvements". – Eljay Sep 02 '18 at 13:38
0

The only way to tell is to look at the assembly language code generated by the compiler. There are all kinds of optimizations that compilers do. The compile could easily change your modulus operator into a bit test instruction.

Performance is a product of system design; not coding.

The speed difference between your two examples is so small that it would be hardly noticed in nearly any application.

user3344003
  • 20,574
  • 3
  • 26
  • 62