Geo*_*ton 10 c# arrays performance
我目前正在开发一个应用程序,负责计算锯齿状阵列的随机排列.
目前,应用程序中的大部分时间都花费在每次迭代中复制数组(总共100万次迭代).在我当前的系统上,整个过程需要50秒才能完成,其中39秒用于克隆阵列.
我的数组克隆例程如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法,安全或不安全,以达到与上述相同的效果,更快?
Mat*_*ted 21
这些都应该适合你.它们都在大约相同的时间内运行,并且都比您的方法快得多.
// 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;
}
Run Code Online (Sandbox Code Playgroud)