Garbage collector is the heart of .NET Framework. The purpose of the Garbage Collector in .NET is to manage the allocation and release of memory in your application.
1. Don’t create big objects with short lifetime
Any object in CLR that is more than 85 000 KB in size are stored in the special heap for big objects. Also they are marked as 2nd generation objects from the start. Creating big objects with small lifetime is bad practice. Why? Garbage collector will need to collect 2nd generation objects more often, and this could lead to performance issues.
2. When GC collects garbage it pauses all managed threads
When garbage collection starts CLR hijacks all managed threads and pauses them. But in fact it doesn’t affect coding, so… nevermind :)
3. You can predict OutOfMemoryException
In some cases if application consume a lot of resources there is a probability of OutOfMemoryException. Not good, yeah? But… you can predict for operations with big memory consumption by using MemoryFailPoint.
using(MemoryFailPoint mfp = new MemoryFailPoint(1500))
//Run code which uses lots of memory.
Console.WriteLine("Not enough memory.");
But be aware. Even if MemoryFailPoint didn’t thrown exception and memory is reserved it’s physically still not allocated. So you only increased a probability of successful memory allocation.
4. Garbage collection takes less than 1ms in zero generation
Yes, it’s so fast.
5. Developers could create immortal objects
Of course it’s only just for fun and definitely bad practice, but these objects will never die (read as not collected by GC).
6. You can manage unmanaged resources.
Sometimes a small managed object could contain a lot of unmanaged resources. For these cases there are 2 methods in GC class.
Using them you can hint how much unmanaged memory is used by object and this will affect when garbage collection will be started.