什么时候是堆栈上分配的固定大小数组?
-
15-11-2019 - |
题
我有以下方法将从套接字流复制到磁盘:
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
关键字
变量声明,但我不想这样做ifn我不必。
解决方案
The buffer
variable will be allocated on the stack, the 8192 byte memory the buffer
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:
"But in the vast majority of programs out there, local variable allocations and deallocations are not going to be the performance bottleneck. "
Ref.
不隶属于 StackOverflow