top of page

.NET / C# Garbage Collection Interview Questions



This video is all about the .NET garbage collector - how it works and how to talk about it in a job interview.


The .NET garbage collector was a revolutionary invention that allowed programmers to stop thinking about memory management and concentrate on solving the customer's problems.


.NET memory comes in two flavors: The Stack, and The Heap.


The Stack is for value types like int, bool and float.


The Heap is for reference types like objects, strings and arrays.


The Heap is further broken down into the Small Object Heap for items under 85K, and the Large Object Heap for all other objects.


For the Small Object Heap, objects are collected by the .NET garbage collector when they are no longer have an active reference. When this occurs, live objects are marked, references are updated and the memory is compacted, overwriting old, dead memory locations.


The Large Object Heap isn't normally compacted, although it's possible to do so in .NET versions of 4.5.1 and greater. Rather, the Large Object Heap has a Free Data Table, which lists locations of free data spaces.


Objects that enter the Small Object Heap are collected on the by "generations." All objects enter the Small Object Heap in Generation 0 - and it will most likely die there. If an object survives collection, it will move to Generation 1. Items in Generation 1 are collected less frequently than Generation 0. But when a collection is run, on Generation 1, Generation 0 is collected as well. If an object in Generation 1 survives collection, it is moved to Generation 2. Generation 2 is used for long-term object storage - mainly items that will last the life of the program.


When Generation 2 is collected, the Large Object Heap is collected as well. This is called a "Full Collection" and it subjects all lower generations to garbage collection as well.


The garbage collector runs under one of three scenarios:

1. The system is low on memory.

2. The a Generation is growing too big.

3. GC.Collect() is called. GC.Collect() manually calls the garbage collector. This should never be done unless under very specific circumstances.


The code and power point for this can be found here:

Archive
Search By Tags
No tags yet.
Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square
bottom of page