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.