5

可能重复:
C#:复制数组的任何更快的方法?

我有一个这样的结构数组:

struct S
{
    public long A;
    public long B;
}

...
S[] s1 = new S[1000000];
...
S[] = new S[s1.Length];
// Need to create a copy here.

我可以使用不安全模式并将结构的源数组复制到字节数组,然后从字节数组复制到结构的目标数组。但这意味着我将不得不分配一个巨大的中间字节数组。有没有办法避免这种情况?是否可以以某种方式将目标数组表示为字节数组并直接复制到那里?

unsafe
{
    int size = Marshal.SizeOf(s0[0]) * s0.Length;
    byte[] tmp = new byte[size];
    fixed (var tmpSrc = &s0[0])
    {
        IntPtr src = (IntPtr)tmpSrc;
        Marchal.Copy(tmpSrc, 0, tmp, 0, size);
    }

    // The same way copy to destination s1 array...
}
4

1 回答 1

0

在 的情况下Buffer.BlockCopy,它将 bytes[] 复制到 byte[] 而不是数组中的逻辑元素。

但这实际上取决于具体情况。

请先测试您的代码Array.Copy并查看。

于 2012-09-27T03:06:08.967 回答