What’s the most efficient way to nest my loops when copying from one multidimensional array to another in C#? The upper and lower bounds of each array are different, so I don’t think Array.Copy() will do the job for me. I currently have the following:
for (int x = lower.X; x <= upper.X; x++)
{
for (int y = lower.Y; y <= upper.Y; y++)
{
for (int z = lower.Z; z <= upper.Z; z++)
{
copy[x, y, z] = Elements[x, y, z];
}
}
}
This is a relatively low-level optimization, so will the compiler take care of this for me? Is there a better way to copy elements of a multidimensional array when the destination has different upper and lower bounds?
Array.Copy will work for you, but only to replace the innermost loop. You will have to calculate the source and destination indicies yourself, but that is certainly doable. The documentation for
Array.Copy(Array, Int32, Array, Int32, Int32)explains how to do the math on indices so you can specify the source and target locations.I highly recommend using Array.Copy everywhere it makes sense to use it, because it is crazy-fast. They do some serious assembler-foo to make it work well.
UPDATE
I am not sure how close this is to correct, because I haven’t tried it, but this is something like how I think it might go: