In this blog, you will learn about the difference between Stack and Heap memory in C#,
Stack Memory
- Very fast access.
- Variables cannot be resized.
- Static memory allocation.
- Variables allocated on the stack are stored directly to the memory.
- The stack is always reserved in a last in first out order(LIFO), the most recently reserved block is always the next block to be freed.
- Variables stored in stacks are only visible to the owner thread.
- In recursion calls, the Stack memory will be quickly filled up compared to heap.
- Stack mostly contains local variable which gets wiped off once they lost scope.
- The stack contains only values for integral types, primitive types, and references to objects.
- Stack memory is used only by one thread of execution.
- The moment stack space is burnout, The .net runtime throws StackOverflowExcepton.Memory.
Heap Memory
- Relatively slower access.
- Variables can be resized.
- Dynamic memory allocation variables allocated on the heap have their memory allocated at runtime.
- You can allocate a block at any time and free it at any time.
- Objects created in the heap are visible to all threads.
- The heap contains the actual object.
- Heap memory is used by all the parts of the application.
- .NET runtime creates a special thread that monitors allocations of heap space called garbage collector.
- Garbage collector only collects heap memory since object is only created in heap.
Summary
In this blog, we have learned the differences between stack and heap memory in C#.