C#中的变量拷贝到缓冲区中,而无需创建垃圾? [英] C# Copy variables into buffer without creating garbage?
问题描述
是否有可能在C#.NET(3.5及以上),以一个变量复制到byte []的缓冲区,而不在此过程中产生的任何垃圾?
Is it possible in C# .Net (3.5 and above) to copy a variable into a byte[] buffer without creating any garbage in the process?
例如:
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));
...
创建字节[]字节中介目标变成垃圾(presuming一个裁判不再追究的话)......
creates the byte[] bytes intermediary object which becomes garbage (presuming a ref is no longer held to it)...
我不知道如果使用位运算符的变量可以直接复制到缓冲区,而无需创建中介的byte []?
I wonder if using bitwise operators the variable can be copied directly into the buffer without creating the intermediary byte[]?
推荐答案
使用指针是最好的,最快的方法: 您可以使用任意数量的变量做到这一点,没有浪费的内存,固定语句有一个小的开销,但它太小了。
Use pointers is the best and the fastest way: You can do this with any number of variables, there is no wasted memory, the fixed statement has a little overhead but it's 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
}
这篇关于C#中的变量拷贝到缓冲区中,而无需创建垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!