Heap versus Stack allocation implications (.NET)

前端 未结 7 1365
梦如初夏
梦如初夏 2020-12-02 16:03

From an SO answer1 about Heap and Stack, it raised me a question: Why it is important to know where the variables are allocated?

At anoth

7条回答
  •  猫巷女王i
    2020-12-02 16:36

    I played a lot with a different benchmarks on stack and heap and I would conclude in following:

    Similar performance for

    • small apps (not too many objects on heap)
    • objects of size < 1KB

    Sligther better stack performance for (1x - 5x faster)

    • Objects of size 1Kb to 100KB

    Much better performance for (up to 100x faster or even more)

    • Large number of objects
    • Big memory presure - a lot allocations per seconds and full memory
    • large objects 10KB - 3MB (I suppose x64 systems)
    • XBox (slow garbage collector)

    The best aproach is array pooling. It is fast as stack, but you don't have such limitation like with stack.

    Another implication of using stack is that it is thread-safe by desing.

    Default memory limit for stack on x64 Windows is 4MB. So you will be safe with allocating not more than 3MB.

提交回复
热议问题