Faster alternative to Convert.ToDouble(string)

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

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

My benchmarks show this to be about 5 times faster than the original for decimal, and up to 12 times if you use ints.


I'm unable to reproduce this. This code tests the speed of Convert.ToDouble.

        int numTests = 10000;
        double sum = 0;
        var sw = Stopwatch.StartNew();
        for (int i = 0; i < numTests; ++i)
        {
            var d = Convert.ToDouble("1.23456");
            sum += d;
        }
        sw.Stop();
        Console.WriteLine("{0} tests @ {1} ms. Avg of {2:N4} ms each", numTests,
           sw.ElapsedMilliseconds, (double)sw.ElapsedMilliseconds/numTests);
        Console.WriteLine("sum = {0}", sum);

With 10,000 calls, I get

10000 tests @ 3 ms. Avg of 0.0003 ms each
sum = 12345.6000000021

That's in release mode, running without the debugger attached.

It's highly unlikely that the problem is with Convert.ToDouble.


You can call double.Parse("1.34515"); which is what Convert.ToDouble wraps.

It may be quicker to call double.TryParse which will avoid the exception overhead.

Tags:

C#

Performance