C# Copy variables into buffer without creating garbage?

后端 未结 2 1350
后悔当初
后悔当初 2021-02-08 01:01

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?

For instance:

int variable         


        
2条回答
  •  长发绾君心
    2021-02-08 01:44

    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
            }
    

提交回复
热议问题