Double.TryParse or Convert.ToDouble - which is faster and safer?

前端 未结 11 1006
滥情空心
滥情空心 2020-11-28 07:28

My application reads an Excel file using VSTO and adds the read data to a StringDictionary. It adds only data that are numbers with a few digits (1000 1000,2 10

11条回答
  •  天涯浪人
    2020-11-28 07:58

    I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.

    Valid input:

    Double.TryParse = 646ms
    Convert.ToDouble = 662 ms
    

    Not much different, as expected. For all intents and purposes, for valid input, these are the same.

    Invalid input:

    Double.TryParse = 612ms
    Convert.ToDouble = ..
    

    Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and Convert.ToDouble with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, Convert.ToDouble's exception raising will ruin your performance.

    So, here's another vote for TryParse with some numbers to back it up.

提交回复
热议问题