Double.TryParse或Convert.ToDouble - 这是更快,更安全?

Double.TryParse或Convert.ToDouble  - 这是更快,更安全?

问题描述:

我的应用程序读取使用VSTO Excel文件,并将该读出的数据为 StringDictionary 。它增加了仅是数字与几个数字的数据(1000 1000,2 1000,34 - 逗号是在俄罗斯标准的分隔符)。

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
}

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

我必须使用 StringDictionary ,而不是字典<字符串,双> 由于以下分析算法问题。

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?

和是它更好地调用 Convert.ToDouble(对象) Convert.ToDouble(字符串)

我没有在Release模式的快速非科学试验。我用两个输入:2.34523和badinput到这两种方法和迭代100万次

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.

有效的输入: Double.TryParse = 646ms Convert.ToDouble = 662毫秒

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.

无效输入: Double.TryParse = 612ms Convert.ToDouble = ..好..它运行很长一段时间。我重新使用1000次迭代,Convert.ToDouble坏输入了8.3秒整个事情。平均出来,这将需要2个多小时。 O_O。我不在乎怎么测试基本是,在无效的输入情况下,Convert.ToDouble的异常引发会毁了你的表现。

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. O_o. I don't care how basic the test is, in the invalid input case, Convert.ToDouble's exception raising will ruin your performance.

所以,这里是另一种的TryParse投带一些数字来支持它。

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