Friday, June 7, 2013

Memory Management of Static variables in .Net

We have seen that the .Net run-time manages the variables and objects in Stacks and Heaps based on their type. Value types are stored in the Stack and reference types are stored in the Heap. This is fine for normal variables, but what happens to static variables.

Static variables cannot be treated like other variables, because static variables and methods in a static class can be accessed directly without creating instances of the class. In this post we shall see on how the .net run-time does memory management for static variables.
The lifetime of a static variable cannot be defined exactly, since it can be called anytime from anywhere just by prefixing the variable with the class name, so these variables should be available at any time of the application execution.

Since static variables have the above requirements they cannot be stored in the stack, as the stack frame will get popped up once the method execution is completed, to overcome this .Net run-time stores the static variables in a special region within the Heap called as High Frequency Heap.

Each App Domain in the .Net run-time has a set of Loader Heaps, which contains High-Frequency Heap, Low-Frequency Heap, and Stub Heap. Objects in the High-Frequency Heap are not Garbage collected, this makes sure that the Static variables are available throughout the life time of the application. If we want to explicitly de-allocate a Static variable then we should set it to null, so that the Garbage collector can clear the memory allocated to the static variable.

Search Flipkart Products:
Flipkart.com

1 comment:

Unknown said...
This comment has been removed by the author.