A guide to Garbage collection for a c++ programmer
For traditional C++ programmers it initially feels a little strange that one is calling “new” and not having to worry about calling delete and freeing the memory on objects. Don’t worry VB programmers have been doing this for years and see how memory efficient most VB applications areJ No seriously I am not advocating a carefree attitude towards memory when programming in .NET, far from it. If one is not careful you could have .NET application which is consuming unnecessarily huge amounts of memory and resources especially if .NET interacts with unmanaged code, which of course it always does. So it is critical to understand.
- When the garbage collector kicks in.
- How does GC mark and decide what is garbage
- When and How does it free the garbage
- ~MyClass() is not a C++ destructor it’s a Finaliser and gets called in a process called finalisation
GC only on allocation and the managed heap is full:
The first thing to know is the garbage collector only “kicks in” when the heap is full and “new” is called. If you have an infinite loop which is just accessing memory and never calling new the Garbage collector cannot kick in:
Lets look at some code lets declare a class MyObject which will occupy some memory
class MyObject
{
private static long m_count = 0;
private long m_id;
private string m_duffmemory;
public MyObject()
{
m_id = m_count++;
m_duffmemory = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
}
}
Ignore the fact that that this code is not threadsafe or that I have not done any sensible error handling. Ok lets create a program that will allocate these objects and put them in a list and then release them from the list. Lets monitor memory usage and see if and when the garbage collector kicks in when we are accessing the list in an infinite loop
static void Main(string[] args)
{
List<MyObject> m_objects = new List<MyObject>();
if (args.Length >= 1)
{
long size = System.Int32.Parse(args[0]);
Console.WriteLine("Allocating {0} objects, Initial Memory Usage {1} ....", size,
System.GC.GetTotalMemory(false));
Console.ReadLine();
for (long i = 0; i < size; i++)
{
m_objects.Add(new MyObject());
}
Console.WriteLine("Allocated {0} objects, Current Memory Usage {1} ....", size, System.GC.GetTotalMemory(false));
Console.ReadLine();
}
bool looped = false;
while (true)
{
if (looped == false)
Console.WriteLine("Freeing Objects Current memory usage {0},", System.GC.GetTotalMemory(false));
for (int i = 0; i < m_objects.Count; i++)
{
m_objects[i] = null;
}
if (looped == false)
{
Console.WriteLine("Current memory usage {0},", System.GC.GetTotalMemory(false));
looped = true;
}
}
Copy the class and the following program into a new console application project and run it up. If you monitor with Performance Montior or bring up Task Manager you will see the while loop is running but the memory usage is not going down. The garbage collector is not kicking in
You can also monitor the memory usage in Performance Monitor. Notice the Paged Bytes will remain the same

Ok now remove the last if(looped == false) check and run it up again. This way it will constantly print out the current memory usage. You will see that, initially the memory usage goes up, then after a while, the GC kicks in!
Notice the memory goes up despite collection being required This is because the collection only takes place when the managed heap is full
A Generational Heaps
The Managed heap is actually divided into 3 generations Gen 0 Gen 1 and Gen2. These heaps are compacted because .NET always knows the size of an object.

Figure 3.
The generations also keep a current location of where the next object is to be allocated.
Freeing the Garbage
We know the CLR is lazy and will only free memory when its needed on allocation so lets see what happens it needs to actually free memory. How does the Garbage collector decide what is garbage? From the Garbage collectors point of view everything is to be considered garbage unless its root (a reference or pointer to the object on the heap) is referenced directly or indirectly on the stack (statics, local variables and CPU registers) Ok so lets say the Garbage collector needs to free memory in order to fulfil the allocation request. A graph or good list is created of all objects which are referenced from the stack.
It is interesting to note that because of the heap generations the Garbage collector does not need to examine the entire heap. We know that the object will first need to be allocated on Gen 0. A Gen 0 collection needs to take place (since gen 0 is full) The objects that are on Gen0 that are referenced still have survived the collection so are promoted (actually moved) to Gen 1. Note the memory is copied from generation heap to generation heap using standard CopyMemory. It can do this because the CLR knows the size of an object. This is why .NET objects have to be pinned if their memory is being passed to unmanaged code
If not referenced then the object is subject to garbage collection the memory is reacclaimed and the “Next Object pointer is reset”. This is the process of a Gen 0 collection
Note if in the promotion the Gen 1, Gen 1 is full. A Gen 1 collection needs to take place (survived objects move to Gen 2) and the same process is followed as for Gen 0 collection and is compacted in the same manner.
Therefore we can see the longer an object stays alive it will eventually end up on Gen 2 (the maximum generation) as collections take place
Also we can see short lived objects they are usually freed on a Gen 0 or Gen 1 collection which are inexpensive However Gen 2 collections are expensive because they involve a Gen 0 and Gen 1 collection also
Note objects over a certain size (I believe its 84K) are not allocated to the Generation heap. The CLR has specific memory (the large memory space) for this which mirrors the standard C runtime heap (i.e. its not compacted like the generation heaps). This is only collected when Gen 2 collections take place
Before the memory is freed The CLR needs to call Finalise for objects that have finalizer before it can reacquire the memory so these objects have togo through a process called Finalisation first before they are subject to collection
Finalization
The Garbage collector has two queues. the Finalization queue and the Freechable Queue. if an object has a finalizer then a pointer is assigned on the Finalization Queue when it is created. When considered garbage the GC checks to see if the object is in the Finalization Queue, if so the pointer is moved to the freechable Queue. For objects on the Freechable queue the Finalisation thread calls the Finalizer and removes the object from the freechable queue and the memory will get freed the next time a GC will occur. It is important to understand objects with Finalizers will possibly go through one or more collection cycles before memory is reclaimed. Microsoft also state for this reason state that you cannot make any assumptions about the order of finalization. Note also the finalizer always gets called be called by another thread (the finalization thread)
Ok so lets get into the real debate about garbage collection C++ programmers argue that all this walking the of roots tree and the finalization process will interrupt the program to free memory and compact the heap. That is true, Certainly one also has to bear in mind that .NET threads must get suspended whilst finalization occurs. However one has to bare in mind that C++ programmers don’t have control how the C runtime manages the heap time is also spent in the heap management algorithms of the c runtime I would advise that if you need to performance tune so much that you need to write your own heap allocation rather then use the standard C runtime heap or you have performance tuned your code so that all dynamically allocated memory up front or just using objects on the stack then you could possibly argue that C++ code will be faster. However if you find you do not require such optimisation and the C++ is constantly allocating and freeing objects on the heap and there are the risks of leaks etc to consider how can one ensure that this will be any faster? Perhaps the overhead of the heap allocation may be more costly overall then the short suspensions which only occur if the Gen 2 collections need to take place. We know Gen 0 collections are very cheap and are done as part of the allocation process
Rules:
If you are referencing unmanaged resources such as native objects, File handles then you must Implement the IDispose interface i.e. dispose method
Dispose should always call SurpressFinalize
If you implement the Dispose interface then you should have a Finalizer defined (since the object may be referenced for a long time) otherwise you should not
Recommendations
Never keep reference to objects unless you really have to.
Try to write code with the garbage collector in mind. Read the following recommendations from Microsoft
http://msdn2.microsoft.com/en-us/library/ms973837.aspx
For more information and my sources
Anyway The following article http://www.devcity.net/Articles/46/1/garbage_collector.aspx
Explains the GC algorthim
www.codeproject.com/dotnet/garbagecollection.asp?msg=341687
It also explains how Weak References work