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.