Which is faster: Stack allocation or Heap allocation

前端 未结 23 1805
悲&欢浪女
悲&欢浪女 2020-11-22 07:40

This question may sound fairly elementary, but this is a debate I had with another developer I work with.

I was taking care to stack allocate things where I could, i

23条回答
  •  情歌与酒
    2020-11-22 07:57

    It has been mentioned before that stack allocation is simply moving the stack pointer, that is, a single instruction on most architectures. Compare that to what generally happens in the case of heap allocation.

    The operating system maintains portions of free memory as a linked list with the payload data consisting of the pointer to the starting address of the free portion and the size of the free portion. To allocate X bytes of memory, the link list is traversed and each note is visited in sequence, checking to see if its size is at least X. When a portion with size P >= X is found, P is split into two parts with sizes X and P-X. The linked list is updated and the pointer to the first part is returned.

    As you can see, heap allocation depends on may factors like how much memory you are requesting, how fragmented the memory is and so on.

提交回复
热议问题