极快的方式克隆一个锯齿形数组的值到第二个数组? [英] Extremely fast way to clone the values of a jagged array into a second array?

查看:128
本文介绍了极快的方式克隆一个锯齿形数组的值到第二个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的一个应用程序,负责计算交错数组的随机排列。

I am currently working on an application that is responsible for calculating random permutations of a jagged array.

目前的应用程序的时间的大部分是花在复制在每次迭代(100万次迭代总数)的阵列。在我目前的系统,整个过程需要50秒才能完成,这些39秒花了克隆数组。

Currently the bulk of the time in the application is spent copying the array in each iteration (1 million iterations total). On my current system, the entire process takes 50 seconds to complete, 39 of those seconds spent cloning the array.

我的数组克隆常规是:

    public static int[][] CopyArray(this int[][] source)
    {
        int[][] destination = new int[source.Length][];
        // For each Row
        for (int y = 0; y < source.Length; y++)
        {
            // Initialize Array
            destination[y] = new int[source[y].Length];
            // For each Column
            for (int x = 0; x < destination[y].Length; x++)
            {
                destination[y][x] = source[y][x];
            }
        }
        return destination;
    }

有什么办法,安全或不安全,要达到上述同样的效果,更快的?

Is there any way, safe or unsafe, to achieve the same effect as above, much faster?

推荐答案

无论这些应该为你工作。他们都运行大约相同数量的时间,都比你的方法要快得多。

Either of these should work for you. They both run in about the same amount of time and are both much faster than your method.

// 100 passes on a int[1000][1000] set size

// 701% faster than original (14.26%)
static int[][] CopyArrayLinq(int[][] source)
{
    return source.Select(s => s.ToArray()).ToArray();
}

// 752% faster than original (13.38%)
static int[][] CopyArrayBuiltIn(int[][] source)
{
    var len = source.Length;
    var dest = new int[len][];

    for (var x = 0; x < len; x++)
    {
        var inner = source[x];
        var ilen = inner.Length;
        var newer = new int[ilen];
        Array.Copy(inner, newer, ilen);
        dest[x] = newer;
    }

    return dest;
}

这篇关于极快的方式克隆一个锯齿形数组的值到第二个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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