是否可以在 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[] bytes 中间对象(假设不再持有 ref)...
我想知道是否可以使用按位运算符将变量直接复制到缓冲区中而无需创建中间 byte[]?
最佳答案
使用指针是最好最快的方法: 您可以使用任意数量的变量来执行此操作,不会浪费内存,fixed 语句有一点开销但它太小了
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
}
关于C# 将变量复制到缓冲区而不产生垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15307431/