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

前端 未结 11 996
滥情空心
滥情空心 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:53

    This is an interesting old question. I'm adding an answer because nobody noticed a couple of things with the original question.

    Which is faster: Convert.ToDouble or Double.TryParse? Which is safer: Convert.ToDouble or Double.TryParse?

    I'm going to answer both these questions (I'll update the answer later), in detail, but first:

    For safety, the thing every programmer missed in this question is the line (emphasis mine):

    It adds only data that are numbers with a few digits (1000 1000,2 1000,34 - comma is a delimiter in Russian standards).

    Followed by this code example:

    Convert.ToDouble(regionData, CultureInfo.CurrentCulture);
    

    What's interesting here is that if the spreadsheets are in Russian number format but Excel has not correctly typed the cell fields, what is the correct interpretation of the values coming in from Excel?

    Here is another interesting thing about the two examples, regarding speed:

    catch (InvalidCastException)
    {
        // is not a number
    }
    

    This is likely going to generate MSIL that looks like this:

    catch [mscorlib]System.InvalidCastException 
    {
      IL_0023:  stloc.0
      IL_0024:  nop
      IL_0025:  ldloc.0
      IL_0026:  nop
      IL_002b:  nop
      IL_002c:  nop
      IL_002d:  leave.s    IL_002f
    }  // end handler
    IL_002f: nop
    IL_0030: return
    

    In this sense, we can probably compare the total number of MSIL instructions carried out by each program - more on that later as I update this post.

    I believe code should be Correct, Clear, and Fast... In that order!

提交回复
热议问题