The Heap
- The heap uses RAM.
- Its size can grow as needed.
- Its scope and lifetime are per application (i.e. per process): when the process exits, all the heap's memory becomes available; multiple threads may share the heap.
- It has expensive memory block de/allocation because: 1. use-case specific logic performs allocation; and 2. allocation may need to be thread safe.
The Stack
- The stack uses RAM.
- Its size is set on thread creation.
- Its scope and lifetime are per thread; when the thread exits, all the stack's memory becomes available.
- It has cheap memory block de/allocation because: 1. allocation follows an enforced First-In-Last-Out pattern: when a function/method/routine runs, a memory block is allocated at the top; when the function returns, that top block becomes free; and 2. allocation need not be thread safe.