Tuesday, April 10, 2007

Benchmarking .NET: Try-Catch vs. TryParse

Inspired by Scott Hanselman article about careful exception handling I decided to investigate the price of catching cast errors. For comparison I chose a TryParse method, which was implemented by .NET 2.0 in all basic types instead of just double in version 1.1.

I wrote small test runner (and practiced generics and delegates along the way). The following two methods were tested:

private static void ConvertTo_Integer__TryParse(string input)
{
int result;
bool success;
success = Int32.TryParse(input, out result);
}

private static void ConvertTo_Integer__TryCatch(string input)
{
int result;
bool success;
try
{
result=Int32.Parse(input);
}
catch
{
success = false;
}
}
Successful operations at no surprise are pretty fast and equal in performance. But in the failure case the traditional try-catch handling is more pricey.

What would happen if there are more operations, like – 1000 of them? Difference is more visible:

In database-related applications a 1000 parse operations in a row are very common. While DateTime.Parse seems to be capable of better performance than Convert.ToDateTime (as latter uses Parse deep inside), the price of a try-catch eats the advantages anyway.

Those are result for Integer and DateTime parsing as a graph:

2 comments:

Anonymous said...

Yes, but after Try.Parse you have to make one additional check for the boolen var status while in the catch block you can directly write whatwver you would want to get away from the situation. Iliia

Michael Goldobin said...

Correct, but equation operation cost is insignificant comparing to the failure handling.


© 2008-2013 Michael Goldobin. All rights reserved