Monday, March 12, 2007

ArrayList vs List<> Generics

when i am working with my new Team in the new place i have got a chance to work with new Generic lists witch has available in .net 2.0. when i am finding information about generic list i understood it's much more better than arraylist. i just checked

Time taken by Collection: 7044.6912 ms
Time taken by Generic: 2898.9216 ms

i just wrote small program using arraylist and the generic list witch is giving the same result.what i understood is on the Generic list you can only assign int (as for the my code.You can supply data type in to List's <> ) to the list - anything else will raise an exception.If you wanted to store a multitude of types, simply inherit from a common base, and use the base as the list identifier.(Use .GetType() ) if i simply says generic list is simple and Safe. :)

if we used arraylist in our code it has to more boxing operations b'coz it can any type.but in generic list is not allowed as i said

here is the code for what i did.


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

namespace Listcompare
{
class Program
{
public static DateTime startTime;
public static DateTime endTime;
public static TimeSpan timeSpan;

private void CheckGenerics()
{
int total = 0;

List lstMyList = new List();
int i = 0;
for (i = 0; i < 20; i++)
lstMyList.Add(i);

for (i = 0; i < 10000000; i++)
foreach (int el in lstMyList)
total += el;

}

private void CheckCollections()
{
int total = 0;
ArrayList al = new ArrayList();
int j = 0;
for (j = 0; j < 20; j++)
al.Add(j);
for (j = 0; j < 10000000; j++)
foreach (int el in al)
total += el;
}

private void Run()
{
startTime = DateTime.Now;
CheckCollections();
endTime = DateTime.Now;
timeSpan = endTime.Subtract(startTime);
Console.Out.WriteLine("Time taken by Collection: " + timeSpan.TotalMilliseconds + " ms");

startTime = DateTime.Now;
CheckGenerics();
endTime = DateTime.Now;
timeSpan = endTime.Subtract(startTime);
Console.Out.WriteLine("Time taken by Generic: " + timeSpan.TotalMilliseconds + " ms");

Console.WriteLine("");
Console.Read();

}
static void Main(string[] args)
{
Program myPgm = new Program();
myPgm.Run();
}
}
}

1 comment:

Anonymous said...

actually, boxing doesn't seem to be the main performance problem... (unboxing is).

see here.