C #: how to efficiently copy a large array of structures?

Possible duplicate:
C #: any faster way to copy arrays?

I have an array of structures 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 structures to an array of bytes, and then from the byte array to the target array of structures. But that means that I have to allocate a huge intermediate array of bytes. Is there any way to avoid this? Is it possible to somehow represent the destination array as a byte array and copy it right 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... } 
+4
source share
2 answers

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

But it really depends on a case by case basis.

First check the Array.Copy code and see.

0
source

Alternative to copying: the fastest approach is to not copy anything.

If you can guarantee that the parts of the array you are interested in do not change, you can issue some alternative interface (i.e. IEnumerable<S> ) for reading such parts.

If you create a copy to create another large array, just consider creating a new array for the second part and output 2 or more arrays as a single object through some interface.

-1
source

Source: https://habr.com/ru/post/1436507/


All Articles