1

One of the most basic operations in programming is figuring out whether the given x is even or odd. The common way to do that is:

ODD(x) = x MOD 2 == 1

The other less popular variant being:

ODD(x) = x AND 1 == 1

It is widely known that those ~bit hacks~ are faster than division. I wonder whether anyone has ever run into a case where the substitution of MOD 2 for AND 1 brought about a significant optimization.

What are the PROs and CONs of each approach, besides time? Personally, I would probably point out that MOD m works for any m, whereas AND 1 cannot be adjusted for other moduli.

Zhiltsoff Igor
  • 1,812
  • 8
  • 24

1 Answers1

4

With modern compiler optimization, I would go for source code clarity in this case.

Look for example at the executable code generated for the AND case (https://godbolt.org/z/sPqM6f) vs. the code generated for the MOD case (https://godbolt.org/z/vM6r3q) with the GCC C++ compiler. They are identical. Not just similar, but identical because the compiler recognized the MOD 2 operation as a special case which can be optimized.

As compiler optimization gets better and better and assembler instructions get more and more involved, I personally tend to go more for source code (including pseudo code) clarity than trying to nudge a compiler into something which I think is an optimization.

nielsen
  • 5,641
  • 10
  • 27
  • Writing for clarity is beneficial, but it is often in the eye of the beholder whether an AND-based or a MOD-based solution provides greater clarity. Community norms and context may play into this. AND (2**n-1) is a common idiom when dealing with bit-fields, for example. – njuffa Mar 05 '21 at 17:49
  • @njuffa You are absolutely right which is the reason why I deliberately did not point at any of them being more "clear" than the other. It depends on the context. The point is that we should be free to choose whichever expression is best suited for the particular case without worrying about performance since that will be the same (of course depending on implementation language/compiler). – nielsen Mar 05 '21 at 21:01
  • 1
    It seems we are in "violent agreement", just expressing it differently :-) FWIW, I cast an up-vote before I wrote the comment. – njuffa Mar 05 '21 at 21:13