Search code examples
c#performancememcpy

Fast memcpy in C#


I want to write a C# method with prototype like this:

void memcpy(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len);

I have 2 options for this method:

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];
    }
}

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;
}

Questions:

A. I guess option 2 is faster than option 1, is it right?

B. Is there another faster method?

Thanks a lot.


Solution

  • Option #2 is broken, since you're using the pointer after the object it points to is no longer fixed. Pointers obtained within a fixed block may only be used inside that same fixed block. And it seems like you should have used Marshal.UnsafeAddrOfPinnedArrayElement anyway (and use it only inside a fixed block pinning the array).

    Have a look at Buffer.BlockCopy.