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

后端 未结 7 1107
清歌不尽
清歌不尽 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:36

    Most other answers are focused on the "what functionality" part of OP's question.
    I believe this will answers the when and why:

    When do you need this?
    For the best worst-case performance with cache locality of multiple small arrays.

    Now in an average app you won't need this, but for realtime sensitive scenarios it gives more deterministic performance: No GC is involved and you are all but guaranteed a cache hit.
    (Because worst-case performance is more important than average performance.)

    Keep in mind that the default stack size in .net is small though!
    (I think it's 1MB for normal apps and 256kb for ASP.net?)

    Practical use could for example include realtime sound processing.

提交回复
热议问题