C # Copy variables to buffer without creating garbage?

Is it possible in C # .Net (3.5 and above) to copy a variable to the byte buffer [] without creating garbage in this process?

For example:

int variableToCopy = 9861; byte[] buffer = new byte[1024]; byte[] bytes = BitConverter.GetBytes(variableToCopy); Buffer.BlockCopy(bytes, 0, buffer, 0, 4); float anotherVariableToCopy = 6743897.6377f; bytes = BitConverter.GetBytes(anotherVariableToCopy); Buffer.BlockCopy(bytes, 0, buffer, 4, sizeof(float)); ... 

creates an intermediate byte [] bytes object that becomes garbage (assuming ref is no longer held) ...

Interestingly, if you use bitwise operators, a variable can be copied directly to the buffer without creating an intermediate byte []?

+5
c # buffer
source share
2 answers

Using pointers is the best and fastest way: you can do it with any number of variables, there is no lost memory, the fixed operator has a bit of overhead, but it is too small

  int v1 = 123; float v2 = 253F; byte[] buffer = new byte[1024]; fixed (byte* pbuffer = buffer) { //v1 is stored on the first 4 bytes of the buffer: byte* scan = pbuffer; *(int*)(scan) = v1; scan += 4; //4 bytes per int //v2 is stored on the second 4 bytes of the buffer: *(float*)(scan) = v2; scan += 4; //4 bytes per float } 
+2
source share

Why can't you just do:

 byte[] buffer = BitConverter.GetBytes(variableToCopy); 

Please note that the array here is not indirect in storage for the original Int32, it is a very large copy.

You might be worried that bytes in your example is equivalent:

 unsafe { byte* bytes = (byte*) &variableToCopy; } 

.. but I assure you that this is not so; This is a byte byte copy of bytes in the Int32 source.

EDIT

Based on your editing, I think you want something like this (an unsafe context is required):

 public unsafe static void CopyBytes(int value, byte[] destination, int offset) { if (destination == null) throw new ArgumentNullException("destination"); if (offset < 0 || (offset + sizeof(int) > destination.Length)) throw new ArgumentOutOfRangeException("offset"); fixed (byte* ptrToStart = destination) { *(int*)(ptrToStart + offset) = value; } } 
+1
source share

All Articles