C# 移动数组的最快方法 [英] C# quickest way to shift array

查看:94
本文介绍了C# 移动数组的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何快速将数组中的所有项目向左移动一位,并用空值填充末尾?

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

例如,[0,1,2,3,4,5,6] 会变成 [1,2,3,4,5,6,null]

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

我说得很快,但我想我的意思是有效.我需要在不创建 List 或其他一些数据结构的情况下执行此操作.这是我需要在尽可能短的时间内完成数十万次的事情.

I said quickly but I guess I meant efficiently. I need to do this without creating a List or some other data structure. This is something I need to do several hundred thousand times in as short amount of time as possible.

推荐答案

这是我的测试工具...

Here's my test harness...

var source = Enumerable.Range(1, 100).Cast<int?>().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);

以下是每个解决方案(8 核 Intel Xeon E5450 @ 3.00GHz)100 万次迭代的性能结果

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

为自己做出选择:)

这篇关于C# 移动数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆