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

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

    Someone's already done the benchmarking. Here are the results. The fastest way if you know what you're converting will always be a valid int, is to use the following method (which a few people have answered above) :

    int value = 0;
    for (int i = 0; i < str.Length; i++)
    {
        value = value * 10 + (str[i] - '0');
    }
    

    Other techniques that were benchmarked were:

    • Convert.ToInt32
    • Int32.TryParse
    • int.Parse

提交回复
热议问题