Stack

  • Used to store variables inside a stack frame for each function
  • Elements are added to the stalk as functions are called
  • Memory is automatically deallocated (by the compiler) as the scope is exited
  • Less space than the heap
  • Faster creation and access time
  • Generally the compiler knows how much space to assign for a stack frame
  • Thread-safe
    • A stack frame is only accessible by the owner thread

Interesting things to note

  • Also known as the Call Stack
  • StackOverFlowError is thrown by the JVM when stack space runs out

Heap

  • Used for Dynamic Memory Allocation
  • More flexible memory management
  • Useful for when the memory needs to remain allocated outside the scope
  • Memory needs to be deallocated (manually or by a Garbage Collector)
  • The heap memory is accessible by all threads (not thread-safe)

Interesting things to note

  • Susceptible to memory leaks if memory is not deallocated properly
  • Also called the heap-space

Differences

  • In most languages the stack is fixed size, whereas the heap is able to resize
  • Accessing a stack frame is easier than in the heap
    • A stack frame is a smaller region of memory
  • The Heap uses a hierarchical data-structure, compared to the Stack which is a Linear type structure (LIFO)
  • The stack has a better locality of reference than the heap-space