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
Heap | Stack |
---|---|
Exists through out the program execution | Automatically deallocate when codeblock exits |
Has garbage collector to clean up | Clean up just by exiting the execution flow |
Object in Heap is normally ones that created with new | For local variables and method parameters |
Can be accessed by multiple thread | Each thread has its own stack, variables are not visible |