Stack Vs Heap

Both stack and heap are stored in RAM.

Stack is faster for access, stack is generated in the compile time. The compiler knows exactly where the stack variables comes from.

Heap is slower for access since it's dynamically allocated. So the compiler doesn't know where the variable coming from.

Stack

Stack store:

  • Local variable
  • Function calls
  • Faster than heap
  • Note: after stack is pop, you will loose access to these data

Heap

Heap store:

  • Reference pointer
  • Object that lasts
  • Slower than stack
  • Note: these data will last for the lifetime of the program.

See: Program structure in memory

HeapStack
Exists through out the program executionAutomatically deallocate when codeblock exits
Has garbage collector to clean upClean up just by exiting the execution flow
Object in Heap is normally ones that created with newFor local variables and method parameters
Can be accessed by multiple threadEach thread has its own stack, variables are not visible