我有一个 List<T>
我希望能够向后复制到数组,这意味着从 List.Count
开始并从列表末尾开始复制可能的 5 个项目并向后工作。我可以用一个简单的反转来做到这一点 for
环形;但是,可能有一种更快/更有效的方法可以做到这一点,所以我想我应该问一下。我可以使用 Array.Copy
吗?不知何故?
最初我使用的是 Queue
因为它会按我需要的正确顺序弹出,但我现在需要一次将多个项目弹出到一个数组中,我认为列表会更快。
最佳答案
看起来 Array.Reverse
具有用于反转数组的 native 代码,该代码有时不适用并且会退回到使用简单的 for 循环。在我的测试中,Array.Reverse
比简单的 for 循环稍微快一点。在这个将包含 1,000,000 个元素的数组反转 1,000 次的测试中,Array.Reverse
大约需要 600 毫秒,而 for 循环大约需要 800 毫秒。
不过,我不建议将性能作为使用 Array.Reverse
的理由。这是一个非常小的差异,您会在将它加载到 List
的那一刻丢失,这将再次循环遍历数组。无论如何,在分析您的应用并确定性能瓶颈之前,您不应该担心性能。
public static void Test()
{
var a = Enumerable.Range(0, 1000000).ToArray();
var stopwatch = Stopwatch.StartNew();
for(int i=0; i<1000; i++)
{
Array.Reverse(a);
}
stopwatch.Stop();
Console.WriteLine("Elapsed Array.Reverse: " + stopwatch.ElapsedMilliseconds);
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
{
MyReverse(a);
}
stopwatch.Stop();
Console.WriteLine("Elapsed MyReverse: " + stopwatch.ElapsedMilliseconds);
}
private static void MyReverse(int[] a)
{
int j = a.Length - 1;
for(int i=0; i<j; i++, j--)
{
int z = a[i];
a[i] = a[j];
a[j] = z;
}
}
关于c# - 向后复制数组?阵列。复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2710899/