什么时候在堆栈上分配固定大小的数组?
我有以下方法将字节从套接字流复制到磁盘:
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);
}
}
我很好奇的是:缓冲区将分配在堆栈上还是在堆栈上 堆?可以肯定的是,我可以使这个方法不安全,并将 fixed
关键字添加到 变量声明,但如果不需要的话我不想这样做。
I have the following method to copy bytes from a socket stream to disk:
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);
}
}
What I am curious about is: will buffer
be allocated on the stack or on the
heap? To be sure, I could make this method unsafe, and add the fixed
keyword to
the variable declaration, but I don't want to do that ifn I don't have to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
buffer
变量将在堆栈上分配,buffer
变量保存的 8192 字节内存将在堆上。你为什么谈论
固定
?你想加快速度吗?几乎肯定不会……引用埃里克·利珀特的话:
参考< /a>.
The
buffer
variable will be allocated on the stack, the 8192 byte memory thebuffer
variable holds the location of will be on the heap.why are you talking about
fixed
? Are you trying to speed things up? It almost certainly won't...To quote Eric Lippert:
Ref.