Monday, 26 October 2015

C# fun

All of us know that look ups are faster than search. OK, but how much? Let us measure.

Stopwatch sw = new Stopwatch();

int count = 100000;

int[] arrayA = new int[count];

int[] arrayB = new int[count];

Dictionary dictA = new Dictionary();

Dictionary dictB = new Dictionary();

Hashtable hashA = new Hashtable();

Hashtable hashB = new Hashtable();

bool[] leftOnlyMatch = new bool[count];

for(int i = 0; i < count; i ++)

{

arrayA[i] = i;

dictA.Add(i, null);

hashA.Add(i, null);

arrayB[i] = i + 5000;

dictB.Add(i + 5000, null);

hashB.Add(i + 5000, null);

}

sw.Start();

for (int i = 0; i < count; i++)

{

var item = arrayA[i];

if(!arrayB.Any(x => x == item))

{

leftOnlyMatch[i] = true;

}

}

sw.Stop();

Console.WriteLine("Time elapsed:" + sw.ElapsedMilliseconds);

sw.Reset();

sw.Start();

for (int i = 0; i < count; i++)

{

var item = arrayA[i];

if (!dictB.ContainsKey(item))

{

leftOnlyMatch[i] = true;

}

}

sw.Stop();

Console.WriteLine("Time elapsed:" + sw.ElapsedMilliseconds);

sw.Reset();

sw.Start();

for (int i = 0; i < count; i++)

{

var item = arrayA[i];

if (!hashB.ContainsKey(item))

{

leftOnlyMatch[i] = true;

}

}

sw.Stop();

Console.WriteLine("Time elapsed:" + sw.ElapsedMilliseconds);

The output is (release mode, 32 GB RAM, 4 dual core processors)

Time elapsed:36244
Time elapsed:1
Time elapsed:2
Press any key to continue . . .


There you go. Dictionary seems slightly faster than Hashtable and it seems only logical.

Fun point

What's wrong with this code?

var testResult = test.Where(x => x == "1111").Select(y => y.Length).First();

There are 2 issues:

1. It assumes that Where clause will always return results.
2. It uses 3 operations for something that is possible with just 1.

var testResult = test.FirstOrDefault(x => x == "1111");
var length = testResult != null ? testResult.Length : 0;








No comments:

Post a Comment