What’s faster: Stack or Heap allocation?

Asked

Viewed 275 times

4

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

I whenever I can make allocations on Stack because for me the growth of Stack is constant in time. And already the allocation performance in Heap depends on the complexity of it at the moment both for allocation and for out-of-location.

In my view this is a question that depends a lot on the compiler being used. But based on GCC, what is the case? Would have the allocation in Heap a low performance compared to allocation in Stack? No difference? Or the difference is so minimal that it doesn’t pay to work with this micro optimization?

1 answer

5


Efficiency

The allocation in Stack is always much faster than the allocation in Heap, as a general rule only means esp, which is the current stack frame pointer in the amount of bytes desired, reserving them for the allocation being made. Something like:

sub esp, 4 

That would set aside 4 bytes for the new Stack

The allocation in Heap you will have to go through the memory manager, which alone will be much slower, but can still incur other types of situations that further penalize efficiency, such as memory fragmentation. In languages without Garbage Collection, such as C/C++, which is allocated in Heap has to be then manually displaced calling free or delete.

Object life

There are still other issues such as the length of life of the object. It should not be forgotten that if the object must persist after the method/function is finished, it will have to be allocated in Heap. All Stack placeholder for a run function is released after it returns.

Optimizations

The 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 it thinks they are not necessary. Often premature optimizations lead to solving problems that in the final factored code do not even exist. You will be advised to optimize when you see that it is a critical code section for your application and can gain considerable efficiency in it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.