可能的重复:
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.
Run Code Online (Sandbox Code Playgroud)
我可以使用不安全模式并将结构的源数组复制到字节数组,然后从字节数组复制到结构的目标数组。但这意味着我将不得不分配一个巨大的中间字节数组。有没有办法避免这种情况?是否有可能以某种方式将目标数组表示为字节数组并直接复制到那里?
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...
}
Run Code Online (Sandbox Code Playgroud)
在 的情况下Buffer.BlockCopy,它将 bytes[] 复制到 byte[],而不是数组中的逻辑元素。
但这确实取决于具体情况。
请先测试您的代码Array.Copy并查看。
| 归档时间: |
|
| 查看次数: |
2930 次 |
| 最近记录: |