954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

TryParse vs Exception

By Ron Whittle on Mar 10th, 2011 5:05 am

Quite commonly I see people using one of the Parse routines then catching the exception thrown if the parse fails. This is, in general, a bad practice as throwing an exception is slower than using the corresponding TryParse method. This short snippet shows the routines that I used to measure the timing of each. The results on 100,000 strings, 1/2 of which were 'bad' was:

TryParse took 1,142 milliseconds
Exception took 56,179 milliseconds


As you can see Exceptions are over 50 times slower. Get into the habit of using TryParse.

Before you bring it up, yes parsing 100,000 strings in a row is probably not a common thing in most software. But consider a website that gets millions of hits a day, or server software that is running constantly. If you can save some processing time, you save on resources, which saves you and/or your company money. And everyone likes to save money :)

static void Try(String[] str) {
    int value;
    for (int i = 0; i < str.Length; i++) {
        if (Int32.TryParse(str[i], out value)) {
            Console.WriteLine("Good");
        } else {
            Console.WriteLine("Bad");
        }
    }
}

static void Except(String[] str) {
    int value;
    for (int i = 0; i < str.Length; i++) {
        try {
            value = Int32.Parse(str[i]);
            Console.WriteLine("Good");
        } catch (Exception e) {
            Console.WriteLine("Bad");
        }
    }
}

Addendum: Most of the time you won't have this great of an error rate (50%). But, you only need about 1 in a 1000 to have a parse error to make TryParse faster than a straight Parse/TryCatch.

If you are 100% sure that there are going to be no parse errors, a straight Parse is about 80% faster.

Momerath
Nearly a Senior Poster
3,384 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

Fantastic! Great snippet!

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

Very nice info. Thanks!

Rynkadink
Newbie Poster
24 posts since Feb 2011
Reputation Points: 28
Solved Threads: 2
 

if (the value being passed == to code within the application)
{
this.methodGreat;
}
else
{
this.methodSucketh;
}

private double d;
public double d2 {get{return d;}}
What if the value being entered in a textbox has to be an double value?
try
{
d = double.Parse(textBox1.text);
this.DialgogResult = DialogResult.Ok;
}
catch
{
this.DialgoResult = DialogResult.Cancel;
}

if you want to show error message to the user Exception can be a plus because it's an exception doesn't always make using the exception bad like this.

try
{
d = double.Parse(textBox1.text);
}
catch(Exception ex)
{
frmMessage msg = new frmMessage(ex);
msg.Title = ex.Message;
msg.ShowDialog();
}
now we can use the exception that we are passing to the frmMessage form to show more datailed information on the exception that occurred;
or we can use a
Console.WriteLine("-------Error Occurred In Application-------");
Console.WriteLine("The Error Occured On " + DateTime.Now.ToLongDateString() + "At " + DateTime.Now.ToShortTimeString());
Console.WriteLine("Application Experienced Error: " + ex.Message);
Console.WriteLine("Would You Like To Retry The Operation? y/n")
string retry = Console.ReadLine().ToLower();
if (retry == "y")
{Application.DoEvents();}

CsharpChico
Junior Poster in Training
72 posts since May 2010
Reputation Points: 12
Solved Threads: 8
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: