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)
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):
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)
if (!Int32.TryParse(value, out result))
And now, when I re-run the test drive code I got blown away by the results – look at that 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:
There is a single conclusion to this post: avoid using Parse+try/catch and start using TryParse. As simple as that.
All the best,