5

Possible Duplicate:
C#: Any faster way of copying arrays?

I have an array of structs like this:

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

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

I can use unsafe mode and copy the source array of structs to a byte array and then from byte array to destination array of structs. But that means I will have to allocate a huge intermediate byte array. Is there a way to avoid this? Is it possible to somehow represent a destination array as a byte array and copy directly there?

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...
}
Community
  • 1
  • 1
Schultz9999
  • 8,717
  • 8
  • 48
  • 87
  • 9
    Have you tried just doing a normal array copy and done performance testing on it? Verify that the normal route isn't too slow before optimizing. – Servy Sep 27 '12 at 02:36
  • @PeterRitchie Removed my comment. Actually using Buffer.BlockCopy may be the to go. Nonetheless the question is still valid. Maybe not from practical point of view :) – Schultz9999 Sep 27 '12 at 02:48
  • Looks like reasonable signpost to the duplicate... Consider not deleting. – Alexei Levenkov Jun 04 '17 at 18:31
  • 1
    I'm voting to re-open as this is specifically about arrays of *structs*, as such the question that was linked to doesn't address this. E.g. BlockCopy is for arrays of primitive types only, not structs. – redcalx Nov 17 '17 at 20:01

1 Answers1

0

In case of Buffer.BlockCopy, it copies bytes[] to byte[] and not logical elements in array.

But this is really dependent on case to case.

Please test your code with Array.Copy first and see.

Schultz9999
  • 8,717
  • 8
  • 48
  • 87
A Developer
  • 1,001
  • 3
  • 12
  • 32