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)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.
{
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;
}
}
Those are result for Integer and DateTime parsing as a graph:

2 comments:
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
Correct, but equation operation cost is insignificant comparing to the failure handling.
Post a Comment