What Is The Difference Between Stack And Heap Memory In C#

In this blog, you will learn about the difference between Stack and Heap memory in C#,

Stack Memory

  1. Very fast access.
  2. Variables cannot be resized.
  3. Static memory allocation.
  4. Variables allocated on the stack are stored directly to the memory.
  5. 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. 
  6. Variables stored in stacks are only visible to the owner thread.
  7. In recursion calls, the Stack memory will be quickly filled up compared to heap.
  8. Stack mostly contains local variable which gets wiped off once they lost scope.
  9. The stack contains only values for integral types, primitive types, and references to objects.
  10. Stack memory is used only by one thread of execution. 
  11. The moment stack space is burnout, The .net runtime throws StackOverflowExcepton.Memory.

Heap Memory

  1. Relatively slower access.
  2. Variables can be resized.
  3. Dynamic memory allocation variables allocated on the heap have their memory allocated at runtime.
  4. You can allocate a block at any time and free it at any time.
  5. Objects created in the heap are visible to all threads.
  6. The heap contains the actual object.
  7. Heap memory is used by all the parts of the application.
  8. .NET runtime creates a special thread that monitors allocations of heap space called garbage collector.
  9. 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#.

Next Recommended Reading How To Use Queue And Stacks In C#