1

C# TryParse Vs Try Catch

Spread the love

C# TryParse Vs Try Catch

This article details the C# benchmark showdown between TryParse Vs Try Catch performance.

C# programmers are undoubtedly familiar with the multiple ways data can be parsed to verify good data while also handling bad data.

 

Each has its advantages and disadvantages depending on the context. I believe most developers would suggest:

  • the Try Catch approach in framework and back-end programming because more information can be given to the client about the error
  • using TryParse if you don’t care about why something fails

 

What isn’t often considered are the performance implications.

Exception handling is expensive. But this Curious Consultant is wondering how expensive?

Let’s find out!

 

The pre-amble about the code and set up

3 string arrays are initialized with 20 string representations of int, bool, and DateTime values. The first 19 are valid; the last value is the string “hello” to purposely cause an exception 5% of the time.

The code then performs the conversions using the TryParse methods followed by the Try Catch structure.

The C# is written in Visual Studio 2015 targeting .Net Framework version 4.7.1 x64. The source code is available at the end of this blog so you can benchmark it on your own system.

 

Which way came out on top?

Because exception handling is naturally expensive, in this TryParse Vs Try Catch race we’re expecting TryParse to come out on top.

But let’s see what happened on my machine.

All times are indicated in seconds.milliseconds format.

Lower numbers indicate faster performance. Winners marked in green.

 

1,000

10,000

100,000

1,000,000

10,000,000

int.TryParse()

00.0000817

00.0007766

00.0075907

00.0820211

00.8331172

int Try Catch

00.0100096

00.0197005

00.1265200

01.5656189

13.2879841

 

bool.TryParse()

00.0000181

00.0001690

00.0010283

00.0082409

00.0790119

bool Try Catch

00.0015470

00.0130745

00.1482046

01.4293894

13.8321639

 

DateTime.TryParse()

00.0001125

00.0007083

00.0077886

00.0784932

00.7890670

DateTime Try Catch

00.0023502

00.0167284

00.1756736

01.7237376

18.0333234

 

The winner – 100x faster!

Unless someone spots a flaw in my code, when there’s a need for speed, the TryParse methods are the only ones that should be considered! Just look at the numbers and time differences! It blew the Try Catch construct out of the water – being 100x faster when there’s an exception 5% of the time.

Check out the speed differences at the 1 million and especially at the 10 million counts where Try-Catch took at least 13 seconds compared to TryParse taking less than a second.

Cool stuff. 🙂

 

The Code:

 


Spread the love

David Lozinski