Ngh*_*Bui 0 c# performance memcpy
我想用这样的原型编写一个C#方法:
void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len);
Run Code Online (Sandbox Code Playgroud)
这个方法有2个选项:
1.
void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len)
{
for (int i = 0; i < len; i++)
{
dst[dstOffset + i] = src[srcOffset + i];
}
}
Run Code Online (Sandbox Code Playgroud)
2.
void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len)
{
IntPtr intPtr = getIntPtr(dst, dstOffset);
System.Runtime.InteropServices.Marshal.Copy(src, srcOffset, intPtr, len);
}
IntPtr getIntPtr(byte[] buffer, int offset)
{
IntPtr intPtr;
unsafe
{
fixed (byte* p1 = buffer)
{
byte* p2 = p1 + offset;
intPtr = (IntPtr)p2;
}
}
return intPtr;
}
Run Code Online (Sandbox Code Playgroud)
问题:
答:我猜选项2比选项1快,是不是?
B.还有另一种更快的方法吗?
非常感谢.
选项#2被破坏,因为您指向的对象不再被修复后使用指针.fixed块内获得的指针只能在同fixed一块内使用.看起来你应该Marshal.UnsafeAddrOfPinnedArrayElement使用它(并且仅在fixed固定阵列的块内部使用它).
| 归档时间: |
|
| 查看次数: |
8160 次 |
| 最近记录: |