We tend to use MOD parity everywhere. Alternating list styles, working with collections...

Just a short. Mathematically speaking, one of the definitions of parity is to determine oddness. A parity of 1 means that a given number is odd, while a parity of 0 means that number is even. This works out for us in alternating lists because what we often do is paint all even rows a different color than all of the odd rows. The most popular parity function is to use modulus arithmetic. I know this is popular because it not only appears throughout large code libraries like Windows Forms nad ASP .NET, but also widely in user sample code.

((i%2)==1) // returns true for odd, false for even

While the MOD parity check is fine and dandy there is a (possibly) faster check. All odd numbers have the first bit set, so you can use AND parity. This is approximately 30% faster than using MOD parity (when the JIT optimizes properly and the same otherwise), and if you are using this a bunch, perhaps several thousands comparisons when building a UI, then you might want to make the switch.

((i&1)==1) // returns true for odd, false for even

I'm not sure what the proper *hints* are, but when the AND parity check gets faster, the MOD check does as well by some small percentage. The rest of the time they are both the same speed. It is possible most of the enhancements come when the methods are very small in size, so adding these into a much larger method might not get you the performance gain. Even adding a third test to the function seems to invoke the slower code-path. Something to think about anyway. I wanted to blog this to leave it as a reminder for myself to check in different scenarios.

Published Friday, October 01, 2004 3:58 AM by Justin Rogers

Comments

Friday, October 01, 2004 2:57 PM by Wallym

# re: We tend to use MOD parity everywhere. Alternating list styles, working with collections...

Nice. I had never thought about it that way. I had merely thought about it as a modulus operation.

Wally

Leave a Comment

(required) 
(required) 
(optional)
(required)