Difference between static memory allocation and dynamic memory allocation:
Any variable created using 'new' operator is allocated space in the heap memory, unlike Other variables which are allocated in stack memory.
- Memory allocated on stack stays in scope as long as it is on the stack. It is destroyed when it is popped off the stack (eg: local variables).
- All memory allocated on the stack is known at compile time. Consequently, this memory can be accessed directly through a variable.
- Since the stack is relatively small, large arrays, structures, classes, and even heavy recursion --> not recommended.
- CPU does efficient use of memory — thus no fragmentation.
- Fast access as it literally uses a single instruction to move the stack pointer down by 10 bytes and thus allocate those bytes for use by a variable.
- Variables allocated in heap memory are retained until they are specifically de-allocated. (But in Java, Garbage Collection feature takes care of that).
- As the precise location of the memory allocated is not known until runtime, the memory has to be accessed indirectly through a pointer.
- Since heap is a big pool of memory, large arrays, structures or classes can be allocated here.
- Inefficient use.
- Slower access.