Faster alternative to Convert.ToDouble(string)

前端 未结 7 2303
陌清茗
陌清茗 2020-12-17 23:35

Is there a faster way to convert a string to double than Convert.ToDouble?

I have monitored System.Conv

7条回答
  •  一整个雨季
    2020-12-18 00:17

    You could try decreasing the number of calls to Thread.CurrentCulture by using the Double.Parse(String, NumberStyles, IFormatProvider) overload. Although I doubt it would make a significant difference.

    It may occur that parsing to another type: float or decimal may win a couple percent.

    Kind of a mad idea, but... You could cache the NumberFormatInfo instance and use reflection to call the internal System.Number.ParseDouble directly. This would decrease the number of calls to NumberFormatInfo.GetInstance(), but to be honest, I'd expect reflection to be much slower.

    The only option left (except for avoiding parsing) is using some custom parsing method. For example, if you define a strict format for the numbers (e.g. #.####), you could probably end up with a faster, yet less flexible and/or safe implementation. But taking into account that built-in parsing is half-native, I doubt you'll win.

    UPDATE

    I've analyzed the .NET code a bit more and found out that NumberFormatInfo is a IFormatProvider. So it seems like the fastest code should be:

    IFormatProvider _CachedProvider = NumberFormatInfo.CurrentInfo;
    var value1 = double.Parse(str1, NumberStyles.Number, _CachedProvider);
    var value2 = double.Parse(str2, NumberStyles.Number, _CachedProvider);
    

    This code should decrease the time spent for parsing preparation as much as it's possible. If you parse a lot of string pairse, you could also extract the IFormatProvider caching to an external code that (possibly) runs a loop and win another couple of milliseconds.

提交回复
热议问题