For example I have some array: byte[,] arr = new byte[4800, 3000];
and I need to get part of that array starting from 512, 600 and ending at 1024, 1200.
How I can do that fast?
All I can think of is this:
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];
but that's a lot of assign operations. Is there any faster way?
You can use Buffer.BlockCopy
to copy a block of contiguous memory from one array to another. For example:
// 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
}
If you're copying complete columns (i.e. startY
is 0, and endY
is originalHeight
) then you could just call Buffer.BlockCopy
once, with the appropriate values.
If you're really thinking about copying lines rather than columns, you might want to consider reordering your arrays so that the y
value comes first - currently you have the whole of the first column, followed by the whole of the second column etc.
See more on this question at Stackoverflow