什么是复制C#多维数组元素的最有效的方法? [英] What's the most efficient way to copy elements of a C# multidimensional array?

查看:271
本文介绍了什么是复制C#多维数组元素的最有效的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中从一个多维数组复制到另一个数组时,嵌套循环的最有效的方法是什么?每个数组的上限和下限是不同的,所以我不会 Array.Copy()将为我做这项工作。我目前有以下:

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会为你工作,但只能替换最内层的循环。你必须自己计算来源和目的地指数,但这当然是可行的。 Array.Copy(Array,Int32,Array, Int32,Int32) 说明如何对索引执行数学运算,以便指定来源和目标位置。

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.

推荐使用Array.Copy随处可见,使用它,因为它是疯狂的快。

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.

更新

我不知道这是多么接近这是正确的,因为我没有尝试,但这是一个像我认为它可能去:

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:

int xLength = upper.X - lower.X + 1;
int yLength = upper.Y - lower.Y + 1;
int zLength = upper.Z - lower.Z + 1;

Array copy = Array.CreateInstance(Elements.GetType(), new { xLength, yLength, zLength }, new {lower.X, lower.Y, lower.Z});

int skippedX = lower.X - Elements.GetLowerBound(0);
int skippedY = lower.Y - Elements.GetLowerBound(1);
int skippedZ = lower.Z - Elements.GetLowerBound(2);

int sourceDim0Size = Elements.GetLength(1) * Elements.GetLength(2);
int sourceDim1Size = Elements.GetLength(2);

for (int x = 0; x < xLength; x++)
{
     for (int y = 0; y < yLength; y++)
     {
         int destinationIndex = x * yLength * zLength + y * zLength;
         int sourceIndex = (x + skippedX) * sourceDim0Size 
                           + (y + skippedY) * sourceDim1Size
                           + skippedZ;
         Array.Copy(Elements, sourceIndex, copy, 0, zLength);
     }
} 

这篇关于什么是复制C#多维数组元素的最有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆