What's Faster: Stack or Heap Allocation? [duplicate]

3

This question may sound elementary but it has generated a good debate with a co-worker.

I can whenever I do allocations in Stack because for me the Stack growth is constant in time. And already the allocation performance in Heap depends on the complexity of the same at the time both for allocation and for deallocation.

In my view this is an issue that depends heavily on the compiler being used. But on the basis of GCC , what is the case? Would the allocation in Heap have a poor performance compared to the allocation in Stack ? There is no difference? Or the difference is so minimal that it does not pay to work with this micro optimization?

    
asked by anonymous 09.08.2017 / 09:18

1 answer

3

Efficiency

Allocation in Stack is always much faster than the allocation in Heap , because as a general rule it only corresponds to the esp , which is the pointer of the current stack frame in the desired number of bytes, for the allocation that is being made. Something like:

sub esp, 4 

That would reserve 4 bytes for the new element in Stack

Allocation in Heap will have to go through the memory manager, which in itself will be much slower, but may still incur other types of situations that further penalize efficiency, such as memory fragmentation. In languages without Garbage Collection, such as C / C ++, what is allocated in Heap must be manually deallocated by calling free or delete .

Object life

There are still other issues such as the lifespan of the object. It should not be forgotten that if the object should persist after the method / function has to be allocated in Heap. Any placeholder in Stack for a run function is freed after it returns.

Optimizations

Optimizations are very dependent on the code in question. In addition the compiler itself already does enough, and may not even declare certain variables if they think they are not needed. Often premature optimizations lead to solving problems that in the final factorized code do not even exist. It will be best to optimize when you see that it is a critical piece of code for your application and that you can gain considerable efficiency in it.

    
09.08.2017 / 11:35