我什么时候需要在C#中使用stackalloc关键字?

Pau*_*ulB 24 c# keyword stackalloc

stackalloc关键字提供哪些功能?何时以及为什么要使用它?

Ste*_*eve 18

来自MSDN:

在不安全的代码上下文中使用,以在堆栈上分配内存块.

C#的一个主要特性是你通常不需要直接访问内存,就像使用malloc或使用C/C++一样new.但是,如果你真的想明确地分配一些内存,那么C#认为这是"不安全的",所以你只能在使用该unsafe设置进行编译时才这样做.stackalloc允许你分配这样的内存.

您几乎肯定不需要使用它来编写托管代码.如果直接访问内存,在某些情况下你可以编写更快的代码是可行的 - 它基本上允许你使用适合某些问题的指针操作.除非你有特定的问题,并且不安全的代码是唯一的解决方案,否则你可能永远不需要这个.

  • StackOverflow的构建使得在互联网上搜索的人可以在这里找到答案(只需要先询问). (2认同)
  • "不是由CLR管理" - 这是正确的但非常误导,因为它在堆栈上分配后会自动在范围/方法的末尾被删除,并且不需要任何进一步的垃圾收集. (2认同)

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)


Ada*_*son 9

保罗,

正如这里的每个人都说的那样,该关键字指示运行时在堆栈而不是堆上进行分配.如果您对这意味着什么感兴趣,请查看此文章.