When is a .net garbage collector not compact gc heap?

I run the following code

StringBuilder sb = new StringBuilder(); Stack stack = new Stack(); SynchronizationContext sc = new SynchronizationContext(); GC.Collect(); Console.WriteLine("GC. First Execution."); stack = null; GC.Collect(); Console.WriteLine("GC. Second Execution."); GC.Collect(); Console.WriteLine("GC. Third Execution."); 

When debugging this code using SOS, I see that after the first execution of the GC addresses, they follow:

 !dso ... 0239b5f8 System.Threading.SynchronizationContext 0239b5a8 System.Collections.Stack 0239b560 System.Text.StringBuilder ... 

After the second execution, there is no "stack" object on the heap, but other addresses:

 !dso ... 0239b5f8 System.Threading.SynchronizationContext 0239b560 System.Text.StringBuilder ... 

So, the stack object was assembled, but the sc (SynchronizationContext) object was not moved to the memory that needs to be compressed. We have a memory gap

 !do 0239b5a8 Free Object Size: 80(0x50) bytes 

After the third run, the situation is the same.

Why is this happening? Why is the "compact" operation not performed in this case?

Thanks.

+4
source share
1 answer

GC is lazy to be effective. It will not actually be free or, as you say, “compact” until it is needed. The object has been moved to the allocation queue.

You can wait a few days and not see how it is cleaned. It will be cleaned when resources are low, and this is necessary.

+3
source

Source: https://habr.com/ru/post/1395185/


All Articles