What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)?

后端 未结 15 1215
南笙
南笙 2021-02-02 06:13

Which of the following code is fastest/best practice for converting some object x?

int myInt = (int)x;

or

int myInt = Convert.T         


        
15条回答
  •  盖世英雄少女心
    2021-02-02 06:38

    foreach(DataRow row in someTable.Rows)
    {
        myInt = (int)row["some int value"];
        myInt2 = Int.Parse(row["some int value"]);
        myInt2 = Convert.ToInt32(row["some int value"]);
    }
    

    For this example, if the value coming from the table is indeed an int value, or comparable database value, then using the

    myInt = (int)row["some int value"];
    

    would be the most efficient, and hence the 'fastest' becuase the

    row["some int value"];
    

    will be a value-type int instance boxed inside an reference-type object instance, so using the explicit type cast will be the quickest becuase as other people said it is an operation not a function call, thereby reducing the cpu operations required. A call to a converion or parse method would require extra cpu operations and hence not be as 'fast'.

提交回复
热议问题