Convert.ToDouble的更快替代品

Ste*_*uhr 6 c# performance

是否存在将String转换为DoubleConvert.ToDouble 更快的方法?

我监视过System.Convert.ToDouble(String)调用并降低了我的应用程序性能.

Convert.ToDouble("1.34515");
Run Code Online (Sandbox Code Playgroud)

Perfomance截图

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]; 
Run Code Online (Sandbox Code Playgroud)

}

继Jeffrey Sax CustomParser之后

Jef*_*Sax 8

通过Double.TryParse使用NumberStylesIFormatProvider(即CultureInfo)的特定缓存实例调用,可以节省大约10%:

var style = System.Globalization.NumberStyles.AllowDecimalPoint;
var culture = System.Globalization.CultureInfo.InvariantCulture;
double.TryParse("1.34515", style, culture, out x);
Run Code Online (Sandbox Code Playgroud)

两者Convert.ToDouble和/ Double.ParseDouble.TryParse必须假设输入可以是任何格式.如果您确定您的输入具有特定格式,则可以编写一个性能更好的自定义解析器.

这是一个转换为decimal.转换double为类似.

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));
}
Run Code Online (Sandbox Code Playgroud)

我的基准测试表明它比原来的快5倍decimal,如果使用整数则高达12倍.

  • 请注意,此自定义解析器有一些限制:1)它允许较少的有效数字,但对于大多数情况,64位应该仍然足够2)它不支持符号3)它没有任何错误处理. (6认同)