.NET + Copying a lot of tricks with memory

In the old days, tricks were used (often for blended frame backgrounds) to copy large chunks of memory from one place to another.

Now, when I work in C #, I found the need to move an array of bytes (about 32 thousand in size) from one memory location to another about 60 times per second.

Somehow, I donโ€™t think that a byte copy in a for loop is optimal here.

Does anyone know a good trick to make this work while remaining in purely managed code?

If not, I'm ready to do some P / Invoking or go into unsafe mode, but I would like to stay manageable, if possible, for reasons related to the platform.

EDIT: Some benchmarking code that I wrote just for fun:

Byte by Byte: 15.6192

4 bytes per cycle: 15.6192

Block Copy: 0

Byte[] src = new byte[65535]; Byte[] dest = new byte[65535]; DateTime startTime, endTime; startTime = DateTime.Now; for (int k = 0; k < 60; k++) { for (int i = 0; i < src.Length; i++) { dest[i] = src[i]; } } endTime = DateTime.Now; Console.WriteLine("Byte by Byte: " + endTime.Subtract(startTime).TotalMilliseconds); startTime = DateTime.Now; for (int k = 0; k < 60; k++) { int i = 0; while (i < src.Length) { if (i + 4 > src.Length) { // Copy the remaining bytes one at a time. while(i < src.Length) { dest[i] = src[i]; i++; } break; } dest[i] = src[i]; dest[i + 1] = src[i + 1]; dest[i + 2] = src[i + 2]; dest[i + 3] = src[i + 3]; i += 4; } } endTime = DateTime.Now; Console.WriteLine("4 Bytes per loop: " + endTime.Subtract(startTime).TotalMilliseconds); startTime = DateTime.Now; for (int k = 0; k < 60; k++) { Buffer.BlockCopy(src, 0, dest,0, src.Length); } endTime = DateTime.Now; Console.WriteLine("Block Copy: " + endTime.Subtract(startTime).TotalMilliseconds); 
+4
source share
1 answer

I think you can count on Buffer.BlockCopy () to do the right thing

http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx

+8
source

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


All Articles