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

前端 未结 4 1421
青春惊慌失措
青春惊慌失措 2020-12-09 05:28

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 applicati

4条回答
  •  無奈伤痛
    2020-12-09 06:02

    You can use Array.Clone for the inner loop:

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

    Another alternative for the inner loop is Buffer.BlockCopy, but I haven't measured it's performance against Array.Clone - maybe it's faster:

    destination[y] = new int[source[y].Length];
    Buffer.BlockCopy(source[y], 0, destination[y], 0, source[y].Length * 4);
    

    Edit: Buffer.BlockCopy takes the number for bytes to copy for the count parameter, not the number of array elements.

提交回复
热议问题