Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't garbage collector in net core 2.0 free all memory

I'm running simple code on net core 2.0 and after garbage collection my program still consume 140 MB of ram. Does anybody know why and how I can reduce it? I also have side question. Are there any differences between garbage collection in console application and web application?

var rand = new Random();

var list = new List<Test>();

for(int i = 0; i < 10_000_000; i++)
{
    list.Add( new Test {
        Id  = i,
        Number = rand.NextDouble(),
        Number1 = rand.NextDouble(),
        Number2 = rand.NextDouble(),
        Number3 = rand.NextDouble(),
        Number4 = rand.NextDouble(),
        Number5 = rand.NextDouble(),
        Number6 = rand.NextDouble(),
        Number7 = rand.NextDouble(),
        Number8 = rand.NextDouble(),

    });
}

Console.WriteLine("End of generation");
Console.ReadLine();

for(int i = 0; i < list.Count; i++)
{
    list[i] = null;
}

list = null;

GC.Collect(1);

GC.WaitForPendingFinalizers();

GC.Collect(2);

GC.WaitForPendingFinalizers();

GC.Collect(3);

GC.WaitForPendingFinalizers();

Console.ReadLine();
like image 985
user9159375 Avatar asked Oct 19 '25 21:10

user9159375


2 Answers

I tested your code, and it is indeed as you described. I took a snapshot and looked at the objects, and there is still a List<Test> in memory.

If you run it in release mode, all memory is freed as expected.

So I would guess, it is a bug behavior in debug mode.

EDIT: Lasse Vågsæther Karlsen made an interesting comment:

Debug extends the lifetime for some objects to the end of the method to allow you to inspect variables.

I tested it and if you put code that produces the list in a separate method, all memory is freed.

like image 178
Fabian S. Avatar answered Oct 22 '25 11:10

Fabian S.


If this reference type (the list) is local to this method JIT compiler can actually allocate it on the stack instead of the heap and with Console.Readline(); stack is never deallocated but I don't really know how you test this.

About the difference between GC, yes I think we had issues once in our company and we actually found out that GC for console applications is different than the one for web application. As far as I remember GC in web app was ran in server mode, don't remember the mode of GC for console apps tho.

More on GC modes here : https://blogs.msdn.microsoft.com/seteplia/2017/01/05/understanding-different-gc-modes-with-concurrency-visualizer/

like image 23
kuskmen Avatar answered Oct 22 '25 11:10

kuskmen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!