更快的替代Convert.ToDouble(string) [英] Faster alternative to Convert.ToDouble(string)
问题描述
是否有比 Convert.ToDouble
更快的更快方式将 string
转换为 double
?
Is there a faster way to convert a string
to double
than Convert.ToDouble
?
我监视了 System.Convert.ToDouble(string)
调用及其对我的应用程序性能的降低.
I have monitored System.Convert.ToDouble(string)
calls and its degrading my app performance.
Convert.ToDouble("1.34515");
杰弗里·萨克斯(Jeffrey Sax)的工作答案:
static decimal[] decimalPowersOf10 = { 1m, 10m, 100m, 1000m, 10000m, 100000m, 1000000m };
static decimal CustomParseDecimal(string input) {
long n = 0;
int decimalPosition = input.Length;
for (int k = 0; k < input.Length; k++) {
char c = input[k];
if (c == '.')
decimalPosition = k + 1;
else
n = (n * 10) + (int)(c - '0');
}
return n / decimalPowersOf10[input.Length - decimalPosition];
}
之后
推荐答案
通过使用 NumberStyles
和 IFormatProvider
(即 CultureInfo
):
var style = System.Globalization.NumberStyles.AllowDecimalPoint;
var culture = System.Globalization.CultureInfo.InvariantCulture;
double.TryParse("1.34515", style, culture, out x);
Convert.ToDouble
和 Double.Parse
或 Double.TryParse
都必须假定输入可以是任何格式.如果您确定输入内容具有特定格式,则可以编写自定义解析器,以实现更好的性能.
Both Convert.ToDouble
and Double.Parse
or Double.TryParse
have to assume the input can be in any format. If you know for certain that your input has a specific format, you can write a custom parser that performs much better.
这里是转换为十进制
的代码.转换为 double
的过程与此类似.
Here's one that converts to decimal
. Conversion to double
is similar.
static decimal CustomParseDecimal(string input) {
long n = 0;
int decimalPosition = input.Length;
for (int k = 0; k < input.Length; k++) {
char c = input[k];
if (c == '.')
decimalPosition = k + 1;
else
n = (n * 10) + (int)(c - '0');
}
return new decimal((int)n, (int)(n >> 32), 0, false, (byte)(input.Length - decimalPosition));
}
我的基准测试表明,对于 decimal
,此速度比原始速度快大约5倍,如果使用int,则最多可以快12倍.
My benchmarks show this to be about 5 times faster than the original for decimal
, and up to 12 times if you use ints.
这篇关于更快的替代Convert.ToDouble(string)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!