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

My application reads an Excel file using VSTO and adds the read data to a StringDictionary . It adds only data, which are digits with several digits (1000 1000.2 1000.34 - comma - this is a separator in Russian standards).

Which is better to check if the current line matches the 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 need to use StringDictionary instead of Dictionary<string, double> due to the following parsing algorithm problems.

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

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

+77
double c # parsing
Feb 25 '09 at 15:23
source share
11 answers

I did a quick unscientific test in Release mode. I used two inputs: "2.34523" and "badinput" in both methods and repeated 1,000,000 times.

Valid input:

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

Not as much as expected. For all purposes and goals, for correct input, they are the same.

Invalid input:

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

Well .. he ran for a long time. I repeated the whole thing using 1000 iterations, and Convert.ToDouble with a bad input took 8.3 seconds. On average, it will take more than 2 hours. I don't care how basic the test is, in the invalid input case, Convert.ToDouble collecting exceptions will ruin your performance.

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

+127
Feb 25 '09 at 15:44
source share
β€” -

For starters, I would use double.Parse , not Convert.ToDouble .

What should you use Parse or TryParse : can you continue working with bad input or is this really an exceptional condition? If this is an exception, use Parse and let it explode if the input is bad. If this is expected and can be handled cleanly, use TryParse .

+45
Feb 25 '09 at 15:29
source share

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

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

Name Convert.ToDouble(string, null)

So it’s faster to call the version of the string.

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 execute double.Parse .

+7
Feb 25 '09 at 15:26
source share

If you are not going to handle the exception, go to TryParse. TryParse is faster because it does not need to deal with the entire exception stack trace.

+7
Feb 25 '09 at 15:26
source share

Usually I try to avoid the Convert class (which means: I do not use it) because I find it very confusing: there are too few hints in the code of what exactly is happening here, since Convert allows a lot of semantically very different conversions to happen with the same same code. This makes it difficult for the programmer to control what exactly is happening.

Therefore, my advice should never use this class. This is also not necessary (with the exception of binary number formatting, since the usual ToString class for number classes does not offer an appropriate method for this).

+7
Feb 25 '09 at 15:27
source share

If you are not 100% sure 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 parsing speed becomes secondary when you throw an exception, because it is not much slower than the exception.

+7
Dec 19 '11 at 3:11
source share

There is a lot of hatred for the Convert class here ... To balance things out, Convert has one advantage - if you are given an object,

 Convert.ToDouble(o); 

can just easily return a value if o is already double (either int or something readily).

Using Double.Parse or Double.TryParse is great if you already have it in a string, but

 Double.Parse(o.ToString()); 

should get the string to parse first and depending on your input, which might be more expensive.

+3
Sep 14 '15 at 20:49
source share

Double.TryParse IMO.

It’s easier for you to handle, you will know exactly where the error occurred.

Then you can handle it as you see fit if it returns false (i.e. could not convert).

+2
Feb 25 '09 at 15:26
source share

I always preferred to use TryParse() methods, because it is going to spit back on the success or failure of the conversion without having to worry about exceptions.

+2
Feb 25 '09 at 15:28
source share

Personally, I find the TryParse method easier to read, which one you really want to use depends on your use case: if errors can be handled locally, you expect errors, and the bool from TryParse is good, otherwise you can just let the exceptions fly.

I would expect TryParse be faster as it avoids the overhead of handling exceptions. But use a comparison tool like the Jon Skeet MiniBench to compare different features.

+1
Feb 25 '09 at 15:29
source share

This is an interesting old question. I add the answer because no one noticed a couple of things with the original question.

Which is faster: Convert.ToDouble or Double.TryParse? Which is safer: Convert.ToDouble or Double.TryParse?

I am going to answer both of these questions (I will update the answer later), but first:

For security, what every programmer missed in this question, this is the line (my selection):

It adds only data, which are digits with several digits (1000 1000.2 1000.34 - comma - this is a separator in Russian standards ).

Following this code example:

 Convert.ToDouble(regionData, CultureInfo.CurrentCulture); 

Interestingly, if the spreadsheets are in Russian format, but Excel incorrectly typed the cell fields, then what is the correct interpretation of the values ​​coming from Excel?

Here is another interesting thing about two examples regarding speed:

 catch (InvalidCastException) { // is not a number } 

This will probably generate an MSIL that looks like this:

 catch [mscorlib]System.InvalidCastException { IL_0023: stloc.0 IL_0024: nop IL_0025: ldloc.0 IL_0026: nop IL_002b: nop IL_002c: nop IL_002d: leave.s IL_002f } // end handler IL_002f: nop IL_0030: return 

In this sense, we can probably compare the total number of MSIL instructions executed by each program - more on this later when I update this post.

I believe that the code should be correct, clear and fast ... In that order!

+1
Dec 04 '18 at 0:01
source share



All Articles