Skip to main content
 首页 » 编程设计

c#之什么时候在栈上分配一个固定大小的数组

2024年02月23日15bjzhanghao

我有以下方法将字节从套接字流复制到磁盘:

 public static void CopyStream(Stream input, Stream output) 
 { 
    // Insert null checking here for production 
    byte[] buffer = new byte[8192]; 
    int bytesRead; 
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) 
    { 
        output.Write(buffer, 0, bytesRead); 
    } 
} 

我比较好奇的是:buffer 是分配在栈上还是分配在 堆?可以肯定的是,我可以使这个方法不安全,并将 fixed 关键字添加到 变量声明,但如果不需要,我不想这样做。

请您参考如下方法:

buffer 变量将分配在栈上,buffer 变量所在的 8192 字节内存将位于堆上。

为什么要谈论固定?你想加快速度吗?它几乎肯定不会...

引用 Eric Lippert 的话:

"But in the vast majority of programs out there, local variable allocations and deallocations are not going to be the performance bottleneck. "

Ref .