A stack is a special area of computer’s memory which stores temporary variables created by a function. In stack, variables are declared, stored and initialized during runtime.
It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased. The stack section mostly contains methods, local variable, and reference variables.
In this tutorial, you will learn,
The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space. It supports Dynamic memory allocation.
The heap is not managed automatically for you and is not as tightly managed by the CPU. It is more like a free-floating region of memory.
Parameter | Stack | Heap |
---|---|---|
Type of data structures | A stack is a linear data structure. | Heap is a hierarchical data structure. |
Access speed | High-speed access | Slower compared to stack |
Space management | Space managed efficiently by OS so memory will never become fragmented. | Heap Space not used as efficiently. Memory can become fragmented as blocks of memory first allocated and then freed. |
Access | Local variables only | It allows you to access variables globally. |
Limit of space size | Limit on stack size dependent on OS. | Does not have a specific limit on memory size. |
Resize | Variables cannot be resized | Variables can be resized. |
Memory Allocation | Memory is allocated in a contiguous block. | Memory is allocated in any random order. |
Allocation and Deallocation | Automatically done by compiler instructions. | It is manually done by the programmer. |
Deallocation | Does not require to de-allocate variables. | Explicit de-allocation is needed. |
Cost | Less | More |
Implementation | A stack can be implemented in 3 ways simple array based, using dynamic memory, and Linked list based. | Heap can be implemented using array and trees. |
Main Issue | Shortage of memory | Memory fragmentation |
Locality of reference | Automatic compile time instructions. | Adequate |
Flexibility | Fixed size | Resizing is possible |
Access time | Faster | Slower |
Here, are the pros/benefits of using stack:
Pros/benefit of using heap memory are:
Cons/Drawbacks of using Stack memory are:
Cons/drawbacks of using Heaps memory are:
You should use heap when you require to allocate a large block of memory. For example, you want to create a large size array or big structure to keep that variable around a long time then you should allocate it on the heap.
However, If you are working with relatively small variables that are only required until the function using them is alive. Then you need to use the stack, which is faster and easier.