What is slower about dynamic memory usage?

This question already has an answer here:

  • Which is faster: Stack allocation or Heap allocation 23 answers

  • Caching issues aside, the CPU stack is just that, a stack, a LIFO list/queue. You remove things from it in the exactly opposite order from the one you put them there. You do not create holes in it by removing something in the middle of it. This makes its management extremely trivial:

    memory[--stackpointer] = value; // push
    value = memory[stackpointer++]; // pop
    

    Or you could allocate a large chunk:

    stackpointer -= size; // allocate
    memset(&memory[stackpointer], 0, size); // use
    

    and free it likewise:

    stackpointer += size; // free
    

    Your heap, OTOH, does not have the LIFO property. And for that reason it must keep track of all allocated blocks individually. Which means, it has to have some kind of list of free blocks and a list of allocated blocks and it needs to look for big enough blocks when allocating and look for the specified block when freeing and then likely do some block splitting and coalescing in the process. The simple stack does not need to do any of this.

    This alone is a significant algorithmic difference between two ways of allocation and deallocation.

    Caching and explicit calls to map physical memory into the virtual address space add up as well, but if you consider them to be equal in both cases, you still have a few instructions vs a few dozen to a few hundred instructions of difference.


    "Better" may not a good way to describe it, but it usually is "Faster" to allocate memory on the stack, as opposed to on the heap. You are correct that it is the allocation of the memory which is slower, not the use of that memory afterwards.

    The reason that heap allocation tends to be slower is that heap managers need to do additional work: they often try to find a block of existing memory that closely approximates the size you are requesting, and when freeing blocks, they typically check adjoining memory areas to see if they can be merged. Stack allocation is simply adding a value to a pointer, nothing more.

    链接地址: http://www.djcxy.com/p/13878.html

    上一篇: 学习C程序设计的资源

    下一篇: 什么是动态内存使用较慢?