Wednesday, 16 July 2014

Try Catch performace

With Try Catch
--------------
Dictionary numbers = new Dictionary();
Stopwatch w = new Stopwatch();
w.Start();
int notFound = 0;
for (int i = 1; i <= 1000000; i++)
{
try
{
int value = numbers[i];
}
catch (KeyNotFoundException)
{
notFound++;
}
}
w.Stop();
Response.Write(notFound);
Response.Write("Elapsed: " + w.ElapsedMilliseconds + ".");
//42284-Milliseconds
=========================
Without Try Catch
-------------------
Dictionary numbers = new Dictionary();
Stopwatch w = new Stopwatch();
w.Start();
int notFound = 0;
for (int i = 1; i <= 1000000; i++)
{
if (!numbers.ContainsKey(i))
{
notFound++;
}
}
w.Stop();
Response.Write(notFound);
Response.Write("Elapsed: " + w.ElapsedMilliseconds + ".");
//9-Milliseconds
-------------