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

July 14. 2011 12:22 PM

rtpHarry

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.

rtpHarry

July 14. 2011 03:36 PM

Shay Friedman

Glad I could help! Smile

Shay Friedman

July 15. 2011 10:49 AM

Lior Tal

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

Lior Tal

July 16. 2011 03:51 PM

pingback

Pingback from syngu.com

Please Use TryParse and Avoid Parse+Try/Catch | C# and .NET | Syngu

syngu.com

February 27. 2012 09:25 AM

pingback

Pingback from firethatmanatonce.mi-water-cmp.net

China brings supermarket concept to North Korea
    (AP) | Fire That Man at Once

firethatmanatonce.mi-water-cmp.net

April 9. 2012 05:28 AM

pingback

Pingback from celebrityblogs.ynpndcevents.org

Senator vows probe of lavish federal gathering (reuters) | Celebrity Blogs

celebrityblogs.ynpndcevents.org

December 19. 2012 05:40 PM

Naaptol Coupons

it was sure a pleasure of mine to make one comment on this blog. Have bookmarked this website for future reference. Will definitely share this info with friends

Naaptol Coupons

January 6. 2013 10:53 AM

Ktechsol

I think blog action day is great. The best charities are more about spreading the word than actually donating.

Ktechsol

January 15. 2013 06:51 PM

kate jackson

Great blog Shay. Worth sharing. Thank you big time! Smile

kate jackson

January 15. 2013 06:57 PM

www.getdiscount.co.uk

Very informative blog Shay. Will definitely share this site.

www.getdiscount.co.uk

March 19. 2013 07:37 AM

Yagi Antennas

Hey just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

Yagi Antennas

March 19. 2013 07:59 AM

Yagi Antennas

Hey just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

Yagi Antennas

March 19. 2013 10:40 AM

dish antennas

Hey just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

dish antennas

March 22. 2013 02:28 PM

Discount Deals

I’m glad that you are promoting environmental awareness. The world needs more people like you to help the environmental cause. Most people need a good reminding every once in awhile (Including myself) that we need to act in an environmentally friendly way.

Discount Deals

March 25. 2013 07:19 PM

studentsdiscount.weebly.com/

This Blog Action Day is one of the best way to help in spreading an awareness for the effects of harmful components that we are using nowadays. I do hope that each of us will be responsible enough to do our part.

studentsdiscount.weebly.com/

April 2. 2013 01:09 PM

What is Necessary for Your iMac Computer

Many thanks for creating the effort to talk about this, I feel strongly about this and enjoy studying a great deal more on this subject. If possible, as you gain knowledge, would you mind updating your weblog with a great deal more info? It’s very useful for me.

What is Necessary for Your iMac Computer

April 30. 2013 02:43 PM

getrealestatevalue.com

Good article! We are linking to this particularly great post on our website. Keep up the good writing.

getrealestatevalue.com

May 14. 2013 03:57 PM

http://www.getonlinegambling.com

I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles.Keep up the good work!

http://www.getonlinegambling.com

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting