C# quickest way to shift array

前端 未结 20 1269
礼貌的吻别
礼貌的吻别 2020-12-01 01:35

How can I quickly shift all the items in an array one to the left, padding the end with null?

For example, [0,1,2,3,4,5,6] would become [1,2,3,4,5,6,null]

Ed

20条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 02:25

    If it absolutely has to be in an array, then I would recommend the most obvious code possible.

    for (int index = startIndex; index + 1 < values.Length; index++)
         values[index] = values[index + 1];
    values[values.Length - 1] = null;
    

    This gives the optimizer the most opportunities to find the best way on whatever target platform the program is installed on.

    EDIT:

    I just borrowed Jason Punyon's test code, and I'm afraid he's right. Array.Copy wins!

        var source = Enumerable.Range(1, 100).Cast().ToArray();
        int indexToRemove = 4;
    
        var s = new Stopwatch();
        s.Start();
        for (int i = 0; i < 1000000; i++)
        {
            Array.Copy(source, indexToRemove + 1, source, indexToRemove, source.Length - indexToRemove - 1);
            //for (int index = indexToRemove; index + 1 < source.Length; index++)
            //    source[index] = source[index + 1]; 
        }
        s.Stop();
        Console.WriteLine(s.Elapsed);
    

    Array.Copy takes between 103 and 150 ms on my machine.

    for loop takes between 269 and 338 ms on my machine.

提交回复
热议问题