Stack and Heap Memory in .NET
Satya Prakash Chhikara
.NET 8 | .NET Core | ASP.NET | MVC | Software Development | Mobile Development | Web Development | ERP | CMS | Microsoft Technologies | AI Automation | DevOps | AWS | Azure
Stack and Heap Memory in .NET
Let’s try to understand what exactly happens when we declare a variable into .NET application.
When we declare a variable into .NET application, it allocates a memory into RAM where it stores
1.????? Name of variable
2.????? Data type of variable
3.????? Value of variable
?
The above image shows what exactly happened in memory. Application allocates memory based upon data type of variable on stack OR heap.
?
Stack and Heap Memory
There are two types of memory allocated into .NET applications, one is stack, and another is heap. Let’s understand by example
When “Statement 1” executed, complier will allocate memory into stack. ?The stack memory is responsible for keeping track of the running memory needed in your application.
?
?
When “Statement 2” is executed, compiler will allocate memory into stack again.
领英推荐
When “Statement 3” is executed, it will allocate memory into heap for class object.
Note:?The reference pointers are allocated on the stack. The statement,?EmployeeDTO employeeDTO,?does not allocate any memory for an instance of?EmployeeDTO.?It only allocates a variable with the name employeeDTO in the stack and sets its value to null. When it hits the new keyword, it allocates memory in the heap.
?
?
Why .NET has 2 types of memories
In C#, primitive data types, such as int, double, bool, etc., hold a single value. On the other hand, the reference data types, or object data types are complex, i.e., an object data type or reference data type can have reference to other objects and other primitive data types.
Because object types hold complex data and further reference of other objects as well, that’s why they are allocated dynamic memory (heap memory), whereas when we declare any variable of primitive data types, complier already know how much memory need to be allocated.
?
How is Heap Memory Freed Up?
The memory allocation on the stack is deallocated when the control moves out from the method, i.e., once the method completes its execution. On the other hand, the memory allocation, which is done on the heap, needs to be de-allocated by the garbage collector.
When an object stored on the heap is no longer used, that means the object does not have any reference pointing. Then, the object is eligible for garbage collection. The garbage collector will de-allocate this object from the heap at some point.
Key Differences Between Stack and Head Memory in .NET:
?
?
?