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

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

    The .NET Framework design guidelines recommend using the Try methods. Avoiding exceptions is usually a good idea.

    Convert.ToDouble(object) will do ((IConvertible) object).ToDouble(null);

    Which will call Convert.ToDouble(string, null)

    So it's faster to call the string version.

    However, the string version just does this:

    if (value == null)
    {
        return 0.0;
    }
    return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
    

    So it's faster to do the double.Parse directly.

提交回复
热议问题