Difference between Stack, Heap and Queue?

Stack, heap, and queue are ways that elements are stored in memory. Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM .

Stack (LIFO) 

  1. Static Memory Allocation
  2. Compile Time
  3. Fast in Access
  4. Last in First Out

Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it’s allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.

Heap (No Order)

  1. Dynamic Memory Allocation
  2. Run Time
  3. Slow
  4. Complex
  5. No Order

Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

Queue (FIFO)

  1. Static Memory Allocation
  2. Compile Time
  3. First in First out 

    a queue is similar to a line we would stand in at a bank to get a teller, or at a grocery store to check out. With a queue, the first one in is the first one out. The mnemonic FIFO is used to describe a queue (First-In-First-Out).

    The program statement queue.add(element) might be used to store an element at the end of a queue. The program statement queue.remove() might be used to remove an item at the front of a queue. Note that the name of the item is not needed when you remove an item from a queue because only the item at the front of the queue can be removed.

Leave a Reply

Your email address will not be published. Required fields are marked *