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

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

    Fastest != Best Practice!

    For example, (int) is almost certainly the fastest because it's an operator rather than a function call, but it will only work in certain situations.

    The best practice is to use the most readable code that won't negatively impact your performance, and 99 times out of 100 an integer conversion isn't driving your app's performance. If it is, use the most appropriate, narrowest conversion you can. Sometimes that's (int). Sometimes it's TryParse(). Sometimes it's Convert.ToInt32().

提交回复
热议问题