Garbage Collector


InterServer Web Hosting and VPS

Garbage Collector

Here we'll look at the Garbage Collector in C# and .NET.

Garbage Collector

The garbage collector which is part of the CLR (Common Language Runtime) is responsible for clearing up parts of the memory which are no longer needed. In my time I've found that in web development, this isn't usually an issue, as page requests are usually short lived and don't generally do anything too heavy, though you need to watch out for leaving objects around such as HttpClient. In desktop application development, or background processes, there's a greater chance of running into a memory issue. The garbage collector has a mode for desktop and a mode for server, to cater for this.

Garbage Collection runs when:


  • Low physical memory
  • Size of heap passes a certain level, which is automatically adjusted
  • GC.Collect() has been called


Stack vs Heap memory:

There are 2 types of memory in .NET, the Stack and the Heap.

Stack

Values types such as Int and enum are stored on the stack, as are reference pointers to objects. The stack works in a LIFO / Last In First Out principle. The parts of the stack memory belonging to a method are cleared when we exit a method.


  • Value types eg int
  • Reference pointers


The stack memory works in a LIFO / Last In First Out principle.

Heap

Reference types are stored on the heap, such as string and object. When we create a reference type, first of all a pointer to the reference type is stored on the stack, and once we use the keyword 'new' then the object is stored on the heap. The pointer on the stack is then pointing to the object in the heap.


  • Reference types eg string and object


Generations

The garbage collector splits objects in the heap based on their lifetimes into 3 different generations, this is so the garbage collection process is more optimised, instead of doing all of it in one go.


Sponsored Links
SolarSystem - AngularJS Demo
SolarSystem - Angular JS Demo

Check out my first Angular JS demo hosted in Azure, it helped win my first Angular contract. Put the sound on.