Faster alternative to Convert.ToDouble(string)

前端 未结 7 2296
陌清茗
陌清茗 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:16

    If you are 100% sure about your source data format and range, you can use:

    string num = "1.34515";
    int len = num.Length - num.IndexOf('.') - 1;
    int intval = Int32.Parse(num.Replace(".", ""));
    double d = (double)intval / PowersOf10[len]; // PowersOf10 is pre-computed or inlined
    

    It worked ~50% faster than Double.Parse for me, but I wouldn't use it in any serious applications - it's extremely limited compared to proper parsing and I can't think of process where you need to parse millions of doubles and a few milliseconds would make the difference.

提交回复
热议问题