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
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.
The faster way to copy objects is not to copy them at all - have you considered this option? If you just need to generate permutations you don't need to copy data on each one - just change the array. This approach will not work well if you need to keep on results of previous calls. In any case review your code to see if you are not copying data more times that you have to.
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;
}
how about serializing/deserializing the array, if you use memory streams and binary serialization, I am thinking that it should be pretty quick.