When would I need to use the stackalloc keyword in C#?

后端 未结 7 1106
清歌不尽
清歌不尽 2021-02-05 04:25

What functionality does the stackalloc keyword provide? When and Why would I want to use it?

7条回答
  •  悲哀的现实
    2021-02-05 04:42

    Stackalloc will allocate data on the stack, which can be used to avoid the garbage that would be generated by repeatedly creating and destroying arrays of value types within a method.

    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.
    }
    

提交回复
热议问题