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 10
I have always preferred using the TryParse()
methods because it is going to spit back success or failure to convert without having to worry about exceptions.
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.
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.
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.
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.