C#将变量复制到缓冲区而不创建垃圾?
是否可以在C#.Net(3.5及更高版本)中将变量复制到byte []缓冲区而不在进程中创建任何垃圾?
例如:
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)); ...
创建byte []字节中间对象,它变成垃圾(假设ref不再持有它)…
我想知道如果使用按位运算符,变量可以直接复制到缓冲区而不创建中间字节[]?
使用指针是最好和最快的方法:你可以用任意数量的变量做这个,没有浪费的内存,固定的语句有一点开销,但它太小了
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 }
为什么你不能这样做:
byte[] buffer = BitConverter.GetBytes(variableToCopy);
请注意,这里的数组不是原始Int32的存储间接,它是一个非常复制的副本。
您可能担心示例中的bytes
相当于:
unsafe { byte* bytes = (byte*) &variableToCopy; }
..但我向你保证,事实并非如此; 它是源Int32中字节的逐字节副本。
编辑 :
根据你的编辑,我认为你想要这样的东西(需要不安全的上下文):
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; } }