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

后端 未结 15 1612
南笙
南笙 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

    It depends on what you expect x to be

    If x is a boxed int then (int)x is quickest.

    If x is a string but is definitely a valid number then int.Parse(x) is best

    If x is a string but it might not be valid then int.TryParse(x) is far quicker than a try-catch block.

    The difference between Parse and TryParse is negligible in all but the very largest loops.

    If you don't know what x is (maybe a string or a boxed int) then Convert.ToInt32(x) is best.

    These generalised rules are also true for all value types with static Parse and TryParse methods.

提交回复
热议问题