Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify odd, even numbers - binary vs. mod

Tags:

Recently I had to identify whether a number is odd or even for a large number of integers. I thought of an idea to identify a number as odd or even by AND-ing it against 1 and comparing the result to 1

x & 1 == 1 // even or odd 

I have never seen this implementation in practice. The most common way you always see is :

x % 2 == 0

I decided to do some performance check on both methods and the binary method seems slightly faster on my machine.

int size = 60000000;
List<int> numberList = new List<int>();
Random rnd = new Random();

for (int index = 0; index < size; index++)
{
    numberList.Add(rnd.Next(size));
}

DateTime start;
bool even;

// regular mod
start = DateTime.Now;
for (int index = 0; index < size; index++)
{
    even = (numberList[index] % 2 == 0);
}
Console.WriteLine("Regualr mod : {0}", DateTime.Now.Subtract(start).Ticks);

// binary 
start = DateTime.Now;
for (int index = 0; index < size; index++)
{
    even = ((numberList[index] & 1) != 1);
}
Console.WriteLine("Binary operation: {0}", DateTime.Now.Subtract(start).Ticks);

Console.ReadKey();

Has anyone seen the binary method implemented ? Any drawbacks ?