Better Performance Using TryParse, instead of Parse in C# ASP.Net

About Parse and TryParse

As software developers, we care about our data and we need to transform data from one form to another. When we try to transform the data, we have the options like Try() and TryParse from Microsoft. Here are the difference.

Parse()

It will return a new data if the transform passed, otherwise, it will throw an exception.

TryParse()

It contains two arguments in this method, the original data variable and the out variable reference for the data transformed. It won’t throw any exception, instead, the out variable will be the default value, “0” or “false”. And TryParse() will return a bool value, indicate the parse success or not.

Test in .Net Console Application

My application is version .Net 4.6.2. In this test, we are using ElapsedTicks to check the tick number for each of our scenarios. For each of the scenario, we run a loop of 1000 times and separate the two approaches in two methods.

The Test Result

Success parse: 1332 ticks
Bad parse: 12281875 ticks
Success tryParse: 365 ticks
Bad tryParse: 380 ticks

From the result, we can tell TryParse has a better performance compared to Parse.

In success parsed case, 1332 ticks vs 365 ticks, two methods are in the same level. When coming to the bad parse case, 12281875 ticks vs 380 ticks, I believe your project manager will prefer using TryParse without a doubt.

To Know More about Boost Performance in C#

I just notice this TryParse from a Chinese book about improve performance in C#, 编写高质量代码:改善C#程序的157个建议( Write C# codes in Quality: 157 suggestions)If you know Chinese, I strongly recommend this book.

16 comments On Better Performance Using TryParse, instead of Parse in C# ASP.Net

Leave a reply:

Your email address will not be published.

Site Footer