Double.TryParse or Convert.ToDouble - which is faster and safer?

120,921

Solution 1

I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.

Valid input:

Double.TryParse = 646ms
Convert.ToDouble = 662 ms

Not much different, as expected. For all intents and purposes, for valid input, these are the same.

Invalid input:

Double.TryParse = 612ms
Convert.ToDouble = ..

Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and Convert.ToDouble with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, Convert.ToDouble's exception raising will ruin your performance.

So, here's another vote for TryParse with some numbers to back it up.

Solution 2

To start with, I'd use double.Parse rather than Convert.ToDouble in the first place.

As to whether you should use Parse or TryParse: can you proceed if there's bad input data, or is that a really exceptional condition? If it's exceptional, use Parse and let it blow up if the input is bad. If it's expected and can be cleanly handled, use TryParse.

Solution 3

The .NET Framework design guidelines recommend using the Try methods. Avoiding exceptions is usually a good idea.

Convert.ToDouble(object) will do ((IConvertible) object).ToDouble(null);

Which will call Convert.ToDouble(string, null)

So it's faster to call the string version.

However, the string version just does this:

if (value == null)
{
    return 0.0;
}
return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);

So it's faster to do the double.Parse directly.

Solution 4

Unless you are 100% certain of your inputs, which is rarely the case, you should use Double.TryParse.

Convert.ToDouble will throw an exception on non-numbers
Double.Parse will throw an exception on non-numbers or null
Double.TryParse will return false or 0 on any of the above without generating an exception.

The speed of the parse becomes secondary when you throw an exception because there is not much slower than an exception.

Solution 5

If you aren't going to be handling the exception go with TryParse. TryParse is faster because it doesn't have to deal with the whole exception stack trace.

Share:
120,921

Related videos on Youtube

abatishchev
Author by

abatishchev

This is my GUID. There are many like it but this one is mine. My GUID is my best friend. It is my life. I must master it as I must master my life. Without me, my GUID is useless. Without my GUID I am useless.

Updated on July 05, 2022

Comments

  • abatishchev
    abatishchev almost 2 years

    My application reads an Excel file using VSTO and adds the read data to a StringDictionary. It adds only data that are numbers with a few digits (1000 1000,2 1000,34 - comma is a delimiter in Russian standards).

    What is better to check if the current string is an appropriate number?

    object data, string key; // data had read
    
    try
    {
      Convert.ToDouble(regionData, CultureInfo.CurrentCulture);
      dic.Add(key, regionData.ToString());
    }
    catch (InvalidCastException)
    {
      // is not a number
    }
    

    or

    double d;
    string str = data.ToString();
    if (Double.TryParse(str, out d)) // if done, then is a number
    {
      dic.Add(key, str);
    }
    

    I have to use StringDictionary instead of Dictionary<string, double> because of the following parsing algorithm issues.

    My questions: Which way is faster? Which is safer?

    And is it better to call Convert.ToDouble(object) or Convert.ToDouble(string) ?

    • John Leidegren
      John Leidegren about 15 years
      FYI, double.TryParse is the same thing as try { result = double.Parse(s); return true; } catch { return false; }. Convert is essentially a wrapper for both with a bunch of overloads. It makes no difference how you do it. But as Jon has pointed out, think about how to handle bad input.
    • Jeff Moser
      Jeff Moser about 15 years
      Double.TryParse isn't the same as double.Parse wrapped in a try..catch. The semantics are the same, but the code path is different. TryParse first verifies that the string is a number using an internal Number.TryStringToNumber, whereas Parse assumes it already is a number/double.
  • Buddy Lee
    Buddy Lee about 13 years
    In addition to the things mentioned above, I just found that Convert.ToDouble() will throw an exception with numbers in scientific notation. Consider this: double toDouble = Convert.ToDouble((-1/30000).ToString()); // will fail double dblParse = Double.Parse((-1/30000).ToString()); // works fine
  • David North
    David North about 13 years
    Jon,Can you elaborate on why you prefer double.Parse over Convert.ToDouble?
  • Jon Skeet
    Jon Skeet about 13 years
    @dnorthut: I rarely want null to be converted to 0 (which Convert.ToDouble does), basically. It's also generally more flexible. I just tend to go for the specific methods...
  • T-moty
    T-moty over 8 years
    +1: i see your point of view, parsing boxed numbers/strings with number inside a System.Object is pretty easy, instead a massive type check. But basically i agree with other answers: Convert.ToSomething() is so much expensive rather than Parse/TryParse, especially in an iteration context
  • user1664043
    user1664043 over 8 years
    To me, Convert.ToDouble(o) has a few easy outs if what's in the box is already a number, but the real killer for Convert is that it doesn't have a .TryToDouble(o, out d); Given how expensive exceptions are (and how confident you are - or not - of the inputs), that's the big extra expense of Convert.
  • Igor Mironenko
    Igor Mironenko over 7 years
    Feedback on this answer: If the questions asks what is faster and safer, the answer should not start with: "Personally" and include guessing like: "I would expect...". This is just personal thoughts and commentary, not a good answer.