C# quickest way to shift array

前端 未结 20 1312
礼貌的吻别
礼貌的吻别 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:24

    Here's my test harness...

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

    Here are the performance results for 1 million iterations of each solution (8 Core Intel Xeon E5450 @ 3.00GHz)

                           100 elements  10000 elements
    For Loop                     0.390s         31.839s 
    Array.Copy()                 0.177s         12.496s
    Aaron 1                      3.789s         84.082s
    Array.ConstrainedCopy()      0.197s         17.658s
    

    Make the choice for yourself :)

提交回复
热议问题