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

标签 c# .net 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));

...

创建成为垃圾的 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/

相关文章:

c# - SQL CLR 存储过程是否可以防止注入(inject)?

c# - 为什么 WPF Presentation 库在 StringBuilder.ToString() 中包装字符串?

c# - C# 中除法的第二次计算时间差为零

c# - ASP.NET Core - 无法在属性 '1' 上设置类型 'System.Int32' 的默认值 'MerchantStatus'

c# - 为什么我不能从 C# 中的子类访问 protected 方法?

c# - 如何将逗号分隔的电子邮件列表与正则表达式匹配?

c# - 制作一个返回 BLOB 的 get api .net core (EF)

c# - 以特定时间间隔执行事件

.net - 何时使用.NET BufferedStream 类?

c# - 使用 streamReader.ReadBlock(缓冲区)导入文件