Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c# - Extremely fast way to clone the values of a jagged array into a second array?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...