I encourage you to run a test similar to the one I pasted below. In this example, using exception handling in my casting takes hundreds of milliseconds seconds to perform 10,000 cast operations (that fail). While my other code takes a few milliseconds.

Summary: Don’t use exceptions for logic. No really, don’t.

static void Main(string[] args)
{
TimeSpan span = TimeSpan.MinValue;
DateTime now = DateTime.Now;

object num = null;

for (int x = 0; x < 1000; x++)
{
for (int y = 0; y < 10; y++)
{
int myNum;
if (num != null && num != DBNull.Value)
{
int.TryParse(num.ToString(), out myNum);
}

//try { int myNum = (int)num; } // 24 seconds
//catch { }
}
}
span = DateTime.Now – now;

Console.Write(span);
Console.Read();
}

Also, if we are in debug, this would take about 25 seconds.



No Responses Yet to “.Net Exception performance”  

  1. No Comments Yet

Leave a Reply