Ste*_*eve 18
来自MSDN:
在不安全的代码上下文中使用,以在堆栈上分配内存块.
C#的一个主要特性是你通常不需要直接访问内存,就像使用malloc或使用C/C++一样new.但是,如果你真的想明确地分配一些内存,那么C#认为这是"不安全的",所以你只能在使用该unsafe设置进行编译时才这样做.stackalloc允许你分配这样的内存.
您几乎肯定不需要使用它来编写托管代码.如果直接访问内存,在某些情况下你可以编写更快的代码是可行的 - 它基本上允许你使用适合某些问题的指针操作.除非你有特定的问题,并且不安全的代码是唯一的解决方案,否则你可能永远不需要这个.
Aar*_*ltz 15
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.
}
Run Code Online (Sandbox Code Playgroud)