ALLINSIGHT

Home of the AlmostImplementedException

Modulus vs Bit Operation

Modulus vs Bit Operation

A while ago i read a question on stackoverflow what method is faster to determine if a number is odd or even in C#. Modulus (i % 2) or a bit operation (i & 1).
And the first answere marked as right was the bit-operation. Everybody knows that this way was faster in C, so it has to be in C# too. But its wrong! Both ways are the same.
Since stackoverflow is a very good forum, they discussed it and came to the same conclusion.

But thats not the reason i write about it. That would be a little bit to sheep 😀

There is a main difference between both ways. Readability!
Most developers came across the modulus way and know it already, but with bit-operations most have to think twice to get what this code does. And thats no good way to write your code.

Yeah its only a single line but i think its a good example of clean code. Have a look at the example below and see for yourself. Even when you know what bove lines do, the first one is easier to read.

So if you have two way to do something, chooce the one which is easier to read (even if it is a little bit slower) instead of the cooler looking one ;-).

In this case it is even better to put this code into a function with a meaningful name and a little description to get clean code. That way you can even choose which implementation suits you more, since it doesn’t have an effect on the readability.

And here the example with clean code:

Share :

Leave a Reply

Your email address will not be published. Required fields are marked *