将变量复制到缓冲区而不产生垃圾

本文关键字:变量 复制 缓冲区 | 更新日期: 2023-09-27 18:02:59

是否有可能在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不再持有它)…

我想知道是否使用按位操作符的变量可以直接复制到缓冲区中,而不创建中间字节[]?

将变量复制到缓冲区而不产生垃圾

使用指针是最好和最快的方法:你可以对任意数量的变量这样做,不会浪费内存,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
        }

你为什么不直接做:

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;
    }
}