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

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

问题描述

我目前正在开发一个应用程序,该应用程序负责计算锯齿状数组的随机排列.

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.

我的阵列克隆例程如下:

My array cloning routine is the following:

    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天全站免登陆