本文介绍了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 而不是 Dictionary.

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(object) 还是 Convert.ToDouble(string) 更好?

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

推荐答案

我在 Release 模式下做了一个快速的非科学测试.我在两种方法中都使用了两个输入:2.34523"和badinput",并迭代了 1,000,000 次.

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 ms

没有太大的不同,正如预期的那样.对于所有意图和目的,对于有效输入,这些都是相同的.

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

无效输入:

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

嗯……它运行了很长时间.我使用 1,000 次迭代重新运行了整个过程,Convert.ToDouble 输入错误需要 8.3 秒.平均下来,需要2个多小时.我不在乎测试有多基础,在无效输入的情况下,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.

所以,这是对 TryParse 的另一个投票,并附上一些数字来支持它.

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

这篇关于Double.TryParse 或 Convert.ToDouble - 哪个更快更安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 07:46