简体   繁体   中英

Fastest way to put a smaller n-dimensional array in a bigger one (2d graphical analogy: paint rectangle on canvas)

Say I have this 10x5 array:

..........
..........
..........
..........
..........

and this 1x2 array:

AB
CD
EF

Now I want to write the second array into the bigger one at position 1/2 (X-pos/Y-pos), deleting all old values (my example is zero based & inclusive). The result would be:

..........
..........
.AB.......
.CD.......
.EF.......

There might be multiple sub arrays with a known overwrite hierarchy, the arrays might have more than 3 dimensions and the arrays contain complex objects.

Is there a best practice to do this in C#?
Is there language agnostic solution?

Okay, Buffer.BlockCopy is significantly faster than copying data byte-by-byte, even after you eliminate bounds checking. Interestingly, it seems that Buffer.BlockCopy does in fact work on 2D arrays :)

So you might want to try something like this:

byte[,] source = new byte[1000, 100];
byte[,] dest = new byte[2048, 2048];

int offsetX = 100;
int offsetY = 20;

int width = source.GetLength(0);
int height = source.GetLength(1);

for (int y = 0; y < height; y++)
{
  Buffer.BlockCopy
  (
    source, y * height, 
    dest, offsetX + dest.GetLength(1) * (y + offsetY), 
    width
  );
}

Basically, assuming that the array is a byte array with X as the first index, and Y as the second, I go one row at a time, blitting the whole row from source to dest at once.

It seems much much faster than simply copying one byte at a time, so I assume that it does actually use DMA instead of using the CPU to copy the bytes.

Do note that this will only be faster if the rows are long enough. If you're copying a single column, it will probably be slower than just copying byte by byte. If you find yourself copying columns more often than rows (ie. width is usually less than height ), you might want to think about inverting the coordinates, ie. swapping X and Y.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM