Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 404
abatishchev Avatar asked Feb 25 '09 15:02

abatishchev


People also ask

What does double TryParse do?

TryParse(String, Double) Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

How do you convert a string to a double in flutter?

For converting a String to a double, the parse() static method of double class can be used.


1 Answers

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.

like image 145
Szymon Rozga Avatar answered Sep 23 '22 01:09

Szymon Rozga