Performance
of generic and non-generic list is well known. But there is a catch. We should
always consider results which comes after JIT compilation. The difference between the test run of the code snippet and running the code after JIT does its job may surprise you.
- Now what happens when you run the test application for performance comparison.
- When you run the application, JIT
runs i.e. Just in Time compiler.
- JIT compiles the application, optimize
the code and finds the best approach to executes the code.
- All these JIT steps are time
consuming which are included in first execution, so the execution time is
always way more than actual run time
- So how you can calculate the actual
run time? Simple, to check the performance of your test application with test
data, call code snippet in a loop.
Example
private static void GenericListPerformance()
{
var genList = new
List<int>() { 10, 100, 13, 19, 14, 100, 99 };
var nonGenList = new ArrayList() { 10, 100, 13, 19, 14, 100, 99 };
var stWatch = Stopwatch.StartNew();
genList.Sort();
stWatch.Stop();
Console.WriteLine("Generic List sorting "+ stWatch.Elapsed.TotalMilliseconds.ToString());
stWatch = Stopwatch.StartNew();
nonGenList.Sort();
stWatch.Stop();
Console.WriteLine("Non Generic List sorting "+ stWatch.Elapsed.TotalMilliseconds.ToString());
}
Here I have created a
simple method to compare the two list ArrayList and List<T>. I have used
Stopwatch which is present in System.Diagnostics namespace of .net framework
and then printed the messages with time.
static void Main(string[] args)
{
for (int i = 0;
i < 5; i++)
{
Console.WriteLine(string.Format("<--------Call Number {0} -------->",i));
GenericListPerformance();
Console.WriteLine();
}
}
Result
See the results.
For first run the execution time is-
For Generic - 0.0263
For Non-Generic – 0.233
For Non-Generic – 0.233
And later it came to be line
Generic – 0.0012, 0.0013, 0.0011,
0.0013
Non-Generic – 0.0032, 0.0026, 0.0026, 0.0029
Non-Generic – 0.0032, 0.0026, 0.0026, 0.0029
Therefor, we should always consider
the JIT time
Subscribe to my blog if you want to
get notified about more detailed analysis of topics. Comment if you have any
question or want me to do some analysis on the topic you want.
Thanks
No comments:
Post a Comment