我从较早的 StackOverflow 帖子中阅读了一个关于何时使用 stackalloc 的示例。现在这个例子让我有点困惑:
public unsafe void DoSomeStuff()
{
byte* unmanaged = stackalloc byte[100];
byte[] managed = new byte[100];
//Do stuff with the arrays
//When this method exits, the unmanaged array gets immediately destroyed.
//The managed array no longer has any handles to it, so it will get
//cleaned up the next time the garbage collector runs.
//In the mean-time, it is still consuming memory and adding to the list of crap
//the garbage collector needs to keep track of. If you're doing XNA dev on the
//Xbox 360, this can be especially bad.
}
现在,如果我错了,请随时纠正我,因为我还是 C# 和一般编程的新手。但是字节不是值类型吗?值类型不是存储在声明它们的地方吗?这是否意味着在此示例中,managed
也存储在堆栈中,并且通过扩展,当此堆栈帧完成并转到调用地址时,内存会自动清理,因此应该以与此managed
相同的方式删除unmanaged
例子?