Nguyen Kim Son

Performance test between generics and collection of Objects

In Project Euler on May 14, 2012 at 12:47 pm

Below is the code in C# for testing the performance of 2 approaches in creating a collection: one by using Object, then implicit casting and the other using generics technique.
In the code, we first fill up 2 stacks, one created by collection of objects, the second created using generics. Both contain lot of elements (5E7). We then calculate the sum of all elements. The first one takes 6.3 secs, while the second one takes 1.3 sec. The reason of more than 5 times difference in execution time is due to the overhead of casting.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DiverseTests
{
class Program
{
private const double M = 5e7;
public static Stack GetStackB4Generics()
{
Stack s = new Stack();
for (int i = 0; i < M; i++)
{
s.Push(i);
}
return s;
}

public static Stack GetStackAfterGenerics()
{
Stack s = new Stack();
for (int i = 0 ; i < M ; i++)
{
s.Push(i);
}
return s;
}

static void Main(string[] args)
{
DateTime now = DateTime.Now;
Stack s1 = GetStackB4Generics();
double sum1 = 0;
while (s1.Count != 0)
{
sum1 += (int)s1.Pop(); //cast
}
Console.WriteLine("Sum of stack 1 is " + sum1);
Console.WriteLine(DateTime.Now.Subtract(now));
now = DateTime.Now;

Stack s2 = GetStackAfterGenerics();
double sum2 = 0;
while (s2.Count != 0)
{
sum2 += s2.Pop(); //no cast
}
Console.WriteLine("Sum of stack 2 is " + sum2);
Console.WriteLine(DateTime.Now.Subtract(now));

}
}
}

Leave a comment