更快的替代Convert

更快的替代Convert

本文介绍了更快的替代Convert.ToDouble的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在的更快办法一个的字符串的转换的双击的比 Convert.ToDouble

Does it exist a faster way to convert a String to Double than Convert.ToDouble ?

我已经监测System.Convert.ToDouble(字符串)调用和降低我的应用程序的性能。

I have monitored System.Convert.ToDouble(String) calls and its degrading my app performance.

Convert.ToDouble("1.34515");



工作回答杰弗里·萨克斯:

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];



}

}

推荐答案

你可以通过调用 Double.TryParse 与特定的缓存实例节省约10%的的NumberStyles 的IFormatProvider (即的CultureInfo ):

You can save about 10% by calling Double.TryParse with specific cached instances of NumberStyles and IFormatProvider (i.e. 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.

下面是一个转换成十进制。转换为双击是相似的。

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));
}



我的基准测试显示,这是比原来快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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:34