C#将变量复制到缓冲区而不创建垃圾?

mar*_*mnl 9 .net c# buffer

是否可以在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));

...
Run Code Online (Sandbox Code Playgroud)

创建byte []字节中间对象变为垃圾(假设ref不再持有)...

我想知道如果使用按位运算符,变量可以直接复制到缓冲区而不创建中间字节[]?

Raf*_*ael 5

使用指针是最好,最快的方法:您可以使用任意数量的变量来执行此操作,不会浪费内存,固定语句的开销很小,但是它太小了

        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
        }
Run Code Online (Sandbox Code Playgroud)

  • 也许要提一下:照顾好所有固定(固定)的对象。它们可能会导致堆碎片,最终可能会使用更多内存。 (2认同)