IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

Please Use TryParse and Avoid Parse+Try/Catch

Recently I’ve run into a piece of class which was operating as the central place for type conversions in the system. While the idea of having such a class doesn’t sound like a problem, the way it’s been implemented definitely is.

Most of the conversion methods looked something like that:

public int ToInt(string value)
{
  try
  {
    return Int32.Parse(value);
  }
  catch
  {
    return DefaultValue;				
  }
}

I took this method for a test drive – I executed it within a loop and put a stopwatch before and after. The next chart demonstrates the results (X=number of loop iterations, Y = execution time in milliseconds):

Parse with try/catch execution time chart

100,000 calls to this ToInt method takes about 10 seconds!

This implementation would have been acceptable if there were no other solution for doing this stuff. But there is ALWAYS another way! and this time this way has a name – TryParse.

TryParse will achieve the same result like Parse but with one major difference – it will not raise an exception once the conversion is unsuccessful but instead it will return false. Changing the ToInt method implementation is quite easy:

public int ToInt2(string value)
{
  int result;
  if (!Int32.TryParse(value, out result))
  {
    return DefaultValue;
  }
  return result;
}

And now, when I re-run the test drive code I got blown away by the results – look at that chart:

TryParse execution time chart

The time for 100,000 conversions dropped from ~10 seconds to ~20 milliseconds! that is about 500% faster!!!

This is the joined chart, which makes the results crystal clear:

Joined results: TryParse vs Parse+try/catch

Conclusion

There is a single conclusion to this post: avoid using Parse+try/catch and start using TryParse. As simple as that.

All the best,
Shay.

kick it on DotNetKicks.com Shout it



Comments (3) -

Wow! That is a massive difference! I'd always thought it was largely a matter of stylistic preference and that the exception was simply being thrown and caught inside the tryparse instead.

Reply

Agreed. This can be generalized - don't throw unneeded exceptions as part of the algorithm for doing something, only to be caught and corrected.
The exception mechanism is pretty expensive and should be avoided if possible Smile

Reply

Pingbacks and trackbacks (3)+

Add comment