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

后端 未结 15 1114
南笙
南笙 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:53

    When optimising a bound data grid in .Net 2, I found almost half the time was spent in various object's ToString() methods that were then used as the inputs of Convert operations. By isolating these cases and by casting to the correct type where possible (since they were rows taken out of a database and the types could be relied upon) this caused a massive increase in speed of that data binding operation.

    So, if you know the type of the thing up front and you'll hit the piece of code enough times, it's worth the effort to cast it directly instead of converting where necessary.

    0 讨论(0)
  • 2021-02-02 06:53

    Not sure about performance, but these methods aren't the same at all. Both Parse and TryParse work with string, the String representation of an object is parsed (see MSDN).

    Converts the string representation of a number to its 32-bit signed integer equivalent.

    Not sure about casting and the Convert class, but cast is only for objects that are already integers in fact but not strongly typed.

    Matthias

    0 讨论(0)
  • 2021-02-02 06:53

    (int) conversion on string won't work, so I dont test it. Convert.ToInt32 reflects as testing the value to null and THEN calling int.Parse, so should in general tend to be slower than int.Parse().

    0 讨论(0)
提交回复
热议问题