Is accessing data in the heap faster than from the stack?

后端 未结 7 1082
北荒
北荒 2020-11-29 00:12

I know this sounds like a general question and I\'ve seen many similar questions (both here and on the web) but none of them are really like my dilemma.

Say I have t

7条回答
  •  一生所求
    2020-11-29 00:55

    Quoting from Jeff Hill's answer:

    The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast. Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be - typically - synchronized with "all" other heap accesses in the program.

    enter image description here

提交回复
热议问题