从二维数组中获取范围的更快方法,而不是将元素一个接一个地分配给另一个数组
本文关键字:一个 元素 另一个 数组 分配 范围 获取 二维数组 方法 | 更新日期: 2023-09-27 18:28:49
例如,我有一个数组:byte[,] arr = new byte[4800, 3000];
,我需要得到该数组的一部分,从512600开始,到10241200结束。
我怎么能这么快?
我所能想到的就是:
int start_x = 512, start_y = 600;
int end_x = 1024, end_y = 1200;
byte[,] new_arr = byte[end_x - start_x, end_y - start_y];
for (int x = start_x; x < end_x; x++)
for (int y = start_y; y < end_y; y++)
new_arr[x - start_x, y - start_y] = arr[x, y];
但这是很多分配操作。有更快的方法吗?
您可以使用Buffer.BlockCopy
将连续内存块从一个数组复制到另一个数组。例如:
// Names changed to be more conventional
int originalHeight = ...; // Original "height" in array
int newHeight = endY - startY;
for (int x = startX; x < endX; x++)
{
Buffer.BlockCopy(
array, x * height + startY, // Copying from here...
newArray, x * newHeight, // To here...
newHeight); // A whole column
}
如果要复制完整的列(即startY
为0,endY
为originalHeight
),则只需调用Buffer.BlockCopy
一次,并使用适当的值。
如果你真的想复制行而不是列,你可能需要考虑重新排序数组,使y
值排在第一位-目前你有第一列的全部,然后是第二列的全部。
您可以通过删除x - start_x
:的不必要的重新计算,使其更加高效
int start_x = 512, start_y = 600;
int end_x = 1024, end_y = 1200;
byte[,] new_arr = byte[end_x - start_x, end_y - start_y];
for (int x = start_x; x < end_x; x++)
{
int target_x = x - start_x;
for (int y = start_y; y < end_y; y++)
new_arr[target_x, y - start_y] = arr[x, y];
}