1

I have 2 snippets with unclear results

This is fine:

List<int> MemoryTest = Enumerable.Repeat(1, 100000).ToList(); 
Console.WriteLine("RAM: {0:0,0} KB", GC.GetTotalMemory(true) / 1024); //542KB

This is fine aswell (30KB appear to be the overhead from the Console)

List<int> MemoryTest = Enumerable.Repeat(1, 100000).ToList();
MemoryTest = null;   
Console.WriteLine("RAM: {0:0,0} KB", GC.GetTotalMemory(true) / 1024); //30KB

Snippet (1) Here I expect not 542KB, because the List<int> is out of scope

{
    List<int> MemoryTest = Enumerable.Repeat(1, 100000).ToList();             
}   
Console.WriteLine("RAM: {0:0,0} KB", GC.GetTotalMemory(true) / 1024); //542KB

Snippet (2) Even a GC.Collect() does not help:

{
    List<int> MemoryTest = Enumerable.Repeat(1, 100000).ToList();             
}
GC.Collect();    
Console.WriteLine("RAM: {0:0,0} KB", GC.GetTotalMemory(true) / 1024); //542KB

Why does my GarbageCollector / Managed Code not clear up RAM as expected?

Byyo
  • 2,163
  • 4
  • 21
  • 35
  • 1
    It clears up RAM as I expect. You need to adjust your expectations :) Also, don't run in a debugger, at all - that will hold locals as long as possible, to aid with debugging. Block scopes and explicit `= null` do not affect the lifetime of locals at all - the only thing that matters is whether the local is used in a possible code path or not. Finally `GC.Collect` isn't enough to force a garbage collection - it's more like a post-it note to the GC to do a collection sometimes soon, even if it doesn't seem to be necessary. – Luaan Mar 21 '16 at 08:51

0 Answers0