是否存在将String转换为Double比Convert.ToDouble 更快的方法?
我监视过System.Convert.ToDouble(String)调用并降低了我的应用程序性能.
Convert.ToDouble("1.34515");
Run Code Online (Sandbox Code Playgroud)

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

通过Double.TryParse使用NumberStyles和IFormatProvider(即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.Parse或Double.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倍.