Heap versus Stack allocation implications (.NET)

前端 未结 7 1354
梦如初夏
梦如初夏 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条回答
  • 2020-12-02 16:49

    Contrary to popular belief, there isn’t that much of a difference between stacks and heaps in a .NET process. Stacks and heaps are nothing more than ranges of addresses in virtual memory, and there is no inherent advantage in the range of addresses reserved to the stack of a particular thread compared to the range of addresses reserved for the managed heap. Accessing a memory location on the heap is neither faster nor slower than accessing a memory location on the stack. There are several considerations that might,in certain cases, support the claim that memory access to stack locations is faster, overall, than memory access to heap locations. Among them:

    1. On the stack, temporal allocation locality (allocations made close together in time) implies spatial locality (storage that is close together in space). In turn, when temporal allocation locality implies temporal access locality (objects allocated together are accessed together), the sequential stack storage tends to perform better with respect to CPU caches and operating system paging systems.
    2. Memory density on the stack tends to be higher than on the heap because of the reference type overhead. Higher memory density often leads to better performance, e.g., because more objects fit in the CPU cache.
    3. Thread stacks tend to be fairly small – the default maximum stack size on Windows is 1MB, and most threads tend to actually use only a few stack pages. On modern systems,the stacks of all application threads can fit into the CPU cache, making typical stack object access extremely fast. (Entire heaps, on the other hand, rarely fit into CPU caches.)

    With that said, you should not be moving all your allocations to the stack! Thread stacks on Windows are limited, and it is easy to exhaust the stack by applying injudicious recursion and large stack allocations.

    0 讨论(0)
提交回复
热议问题