Why is memory allocation on heap MUCH slower than on stack?

前端 未结 4 1417
陌清茗
陌清茗 2020-12-04 13:11

I have been told this many times. But I don\'t know WHY...What extra cost is involved when allocating memory from heap? Is it hardware related? Is it related to CPU cycles?

4条回答
  •  自闭症患者
    2020-12-04 13:43

    Because the heap is a far more complicated data structure than the stack.

    For many architectures, allocating memory on the stack is just a matter of changing the stack pointer, i.e. it's one instruction. Allocating memory on the heap involves looking for a big enough block, splitting it, and managing the "book-keeping" that allows things like free() in a different order.

    Memory allocated on the stack is guaranteed to be deallocated when the scope (typically the function) exits, and it's not possible to deallocate just some of it.

提交回复
热议问题