TryParse vs Exception

Momerath 0 Tallied Votes 561 Views Share

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 :)

ddanbe commented: Great snip! +9
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");
        }
    }
}
Momerath 1,327 Nearly a Senior Poster Featured Poster

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.

commented: +++++++++ +1
ddanbe 2,724 Professional Procrastinator Featured Poster

Fantastic! Great snippet!

Rynkadink 18 Newbie Poster

Very nice info. Thanks!

CsharpChico 1 Junior Poster in Training

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();}

Mickey_1 0 Newbie Poster

CsharpChico, here is the revised code.
I hope you understand why you were wrong

What if the value being entered in a textbox has to be an double value?

bool doubleSuccess
double b;
doubleSuccess =  double.TryParse(textBox1.text, out b);
if (doubleSuccess)
this.DialgogResult = DialogResult.Ok;
}
else
{
this.DialgoResult = DialogResult.Cancel;
}

NEXT

double b;
bool doubleSuccess = false;

doubleSuccess = double.TryParse(textBox1.text, out b);
if (!doubleSuccess)
{

string msg = "ParsingFailed: Expected a double as the index data from this stock"; 
frmMessage msg = new frmMessage();
msg.Title = message;
msg.ShowDialog();
}

sending exceptions to the user is a HUGE NO NO
and if you want this for debug, there is no need. solve the problem and test the cases.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.