向后复制一个数组? Array.Copy? [英] Copy an array backwards? Array.Copy?

查看:157
本文介绍了向后复制一个数组? Array.Copy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< T> ,我希望能够复制到一个数组倒退,这意味着从开始 List.Count 复制也许5个项目开始在列表的末尾和向后工作的方式。我可以用一个简单的反向循环做到这一点;但有可能是这样做所以更快/更有效的方式,我想我应该问。我可以用 Array.Copy 不知何故?

I have a List<T> that I want to be able to copy to an array backwards, meaning start from List.Count and copy maybe 5 items starting at the end of the list and working its way backwards. I could do this with a simple reverse for loop; however there is probably a faster/more efficient way of doing this so I thought I should ask. Can I use Array.Copy somehow?

本来我是用队列作为以正确的顺序,我需要弹出它关闭,但我现在需要一次多个项目中弹出到一个数组和我想到了一个列表会更快。

Originally I was using a Queue as that pops it off in the correct order I need, but I now need to pop off multiple items at once into an array and I thought a list would be faster.

推荐答案

看起来 Array.Reverse 具有本地code扭转数组有时不申请并会回落到使用一个简单的for循环。在我的测试 Array.Reverse 是不是一个简单的for循环非常稍快。在倒车1,000,000元素的数组1000次的这种测试, Array.Reverse 约为600毫秒,而一个for循环大约是800毫秒。

Looks like Array.Reverse has native code for reversing an array which sometimes doesn't apply and would fall back to using a simple for loop. In my testing Array.Reverse is very slightly faster than a simple for loop. In this test of reversing a 1,000,000 element array 1,000 times, Array.Reverse is about 600ms whereas a for-loop is about 800ms.

我不会推荐性能为理由,使用 Array.Reverse 虽然。这是一个非常微小的差别,你就会失去你加载分钟到列表将遍历数组这再次。无论如何,你不应该担心的表现,直到你异形您的应用程序,并确定了性能瓶颈。

I wouldn't recommend performance as a reason to use Array.Reverse though. It's a very minor difference which you'll lose the minute you load it into a List which will loop through the array again. Regardless, you shouldn't worry about performance until you've profiled your app and identified the performance bottlenecks.

    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;
        }
    }

这篇关于向后复制一个数组? Array.Copy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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