C# Double.TryParse 或 Convert.ToDouble - 哪个更快更安全?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/586436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:16:51  来源:igfitidea点击:

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

c#.netparsingdouble

提问by abatishchev

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

我的应用程序使用 VSTO 读取 Excel 文件并将读取的数据添加到StringDictionary. 它只添加带有几位数字的数据(1000 1000,2 1000,34 - 逗号是俄罗斯标准中的分隔符)。

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 StringDictionaryinstead of Dictionary<string, double>because of the following parsing algorithm issues.

我必须使用StringDictionary而不是Dictionary<string, double>因为以下解析算法问题。

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

我的问题:哪种方式更快?哪个更安全?

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

打电话好Convert.ToDouble(object)还是Convert.ToDouble(string)打好?

采纳答案by Szymon Rozga

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.

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

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.ToDoublewith 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.

嗯..它运行了很长时间。我使用 1,000 次迭代重新运行整个过程Convert.ToDouble,输入错误需要 8.3 秒。平均下来,需要2个多小时。我不在乎测试有多基本,在无效输入的情况下,Convert.ToDouble异常引发会破坏你的表现。

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

所以,这是另一个投票,TryParse有一些数字来支持它。

回答by Jeff Moser

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

.NET Framework 设计指南建议使用 Try 方法。避免异常通常是一个好主意。

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

Convert.ToDouble(object)会做 ((IConvertible) object).ToDouble(null);

Which will call Convert.ToDouble(string, null)

哪个会调用 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.Parsedirectly.

所以double.Parse直接做会更快。

回答by Damien

Double.TryParse IMO.

Double.TryParse 海事组织。

It is easier for you to handle, You'll know exactly where the error occurred.

您更容易处理,您将确切知道错误发生的位置。

Then you can deal with it how you see fit if it returns false (i.e could not convert).

然后,如果它返回 false(即无法转换),您可以按照您认为合适的方式处理它。

回答by Aaron Palmer

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.

如果您不打算处理异常,请使用 TryParse。TryParse 更快,因为它不必处理整个异常堆栈跟踪。

回答by Konrad Rudolph

I generally try to avoid the Convertclass (meaning: I don't use it) because I find it very confusing: the code gives too few hints on what exactly happens here since Convertallows a lot of semantically very different conversions to occur with the same code. This makes it hard to control for the programmer what exactly is happening.

我通常会尽量避免使用Convert该类(意思是:我不使用它),因为我发现它非常令人困惑:代码给出的关于此处究竟发生了什么的提示太少,因为Convert允许使用相同的代码发生许多语义上非常不同的转换. 这使得程序员很难控制到底发生了什么。

My advice, therefore, is never to use this class. It's not really necessary either (except for binary formatting of a number, because the normal ToStringmethod of number classes doesn't offer an appropriate method to do this).

因此,我的建议是永远不要使用这个类。这也不是真正必要的(除了数字的二进制格式,因为ToString数字类的正常方法没有提供合适的方法来做到这一点)。

回答by TheTXI

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.

我一直更喜欢使用这些TryParse()方法,因为它会吐出转换的成功或失败,而不必担心异常。

回答by Jon Skeet

To start with, I'd use double.Parserather than Convert.ToDoublein the first place.

首先,我会使用double.Parse而不是Convert.ToDouble首先。

As to whether you should use Parseor TryParse: can you proceed if there's bad input data, or is that a really exceptional condition? If it's exceptional, use Parseand let it blow up if the input is bad. If it's expected and can be cleanly handled, use TryParse.

至于您是否应该使用Parseor TryParse:如果输入数据不好,您可以继续吗,或者这是一个非常特殊的情况?如果它是特殊的,请使用Parse并在输入不好时让它爆炸。如果这是预期的并且可以干净地处理,请使用TryParse.

回答by David Schmitt

Personally, I find the TryParsemethod easier to read, which one you'll actually want to use depends on your use-case: if errors can be handled locally you are expecting errors and a bool from TryParseis good, else you might want to just let the exceptions fly.

就我个人而言,我发现该TryParse方法更易于阅读,您实际上想要使用哪种方法取决于您的用例:如果可以在本地处理错误,您就会期待错误并且来自的 boolTryParse很好,否则您可能只想让例外飞。

I would expect the TryParseto be faster too, since it avoids the overhead of exception handling. But use a benchmark tool, like Jon Skeet's MiniBenchto compare the various possibilities.

我希望TryParse它也更快,因为它避免了异常处理的开销。但是使用基准工具,例如Jon Skeet 的 MiniBench来比较各种可能性。

回答by Chase

Unless you are 100% certain of your inputs, which is rarely the case, you should use Double.TryParse.

除非您 100% 确定您的输入(这种情况很少发生),否则您应该使用 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.

当您抛出异常时,解析速度变得次要,因为没有比异常慢多少。

回答by user1664043

Lots of hate for the Convert class here... Just to balance a little bit, there is one advantage for Convert - if you are handed an object,

很多人讨厌这里的 Convert 类......只是为了平衡一点,Convert 有一个优势——如果你拿到一个对象,

Convert.ToDouble(o);

can just return the value easily if o is already a Double (or an int or anything readily castable).

如果 o 已经是 Double (或 int 或任何易于转换的东西),则可以轻松返回该值。

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

如果您已经在字符串中使用 Double.Parse 或 Double.TryParse,那么使用它是很棒的,但是

Double.Parse(o.ToString());

has to go makethe string to be parsed first and depending on your input that could be more expensive.

已去做出的字符串,第一,并根据您的输入,可能是更昂贵的解析。