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

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

    Extending the test of Eric Cosky by alternatives from Sam Allen, i found that if you know that your string is a valid integer, then parsing it by yourself is much faster.

    I extended the test by the following cases:

        timer1000.Measure("IntParseFast", 10, delegate
        {
            result = Misc.IntParseFast(strInput);
        });
    
        timer1000.Measure("IntParseUnsafe", 10, delegate
        {
            result = Misc.IntParseUnsafe(strInput);
        });
    

    With the following implementations:

    public static int IntParseFast(string value)
    {
        int result = 0;
        int length = value.Length;
        for (int i = 0; i < length; i++)
        {
            result = 10 * result + (value[i] - 48);
        }
        return result;
    }
    
    public unsafe static int IntParseUnsafe(string value)
    {
        int result = 0;
        fixed (char* v = value)
        {
            char* str = v;
            while (*str != '\0')
            {
                result = 10 * result + (*str - 48);
                str++;
            }
        }
        return result;
    }
    

    I get the following results:

    IntCaint.Parse                5,495
    IntCaConvert.ToInt32          5,653
    IntCaIntParseFast             1,154
    IntCaIntParseUnsafe           1,245
    

提交回复
热议问题