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 []?
markmnl
source share