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.