Why does garbage collection kick in during a small profiling session?

I am noob in the area of memory profiling and still trying to grasp some concepts.

I am trying to profile the following piece of code with the hope of finding the information about the boxed enumerator "List<string>+Enumerator"...I actually find it as in the below screen shot...

My question is: This is a very small profiling session and finishes pretty fast. Before I enter any key at the "End" of the program, I take a snapshot...Now why would I see the information related to objects being collected in this snapshot?...like why would garbage collection kick in...is it really because there is memory pressure like is it because the Gen 0 got filled up quickly and GC had to kick in...sorry I am not very clear in this area, so please forgive my naive questions

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("Begin");

        Console.ReadLine();

        Goo();

        Console.WriteLine("End");

        Console.ReadLine();

    }

    private static void Goo()

    {

        var list = new List<string>();

        for (var i = 0; i < 1000; i++)

        {

            Foo(list);

        }

    }

    private static void Foo(IEnumerable<string> strings)

    {

        foreach (var str in strings)

        {

        }

    }

}

gc.PNG

0
2 comments

Hi,
You asked a very good question.

In normal situation these objects should not be collected at the "End" point if there is enough memory in the system. The reason why they were collected is dotMemory causes garbage collection to get a memory snapshot.
This is how Microsoft Profiling API works, it requires to call full GC to obtain a graph of objects held in memory.

If you for some reason want to  investigate these objects, return List<string> object from the method Goo and use GC.KeepAlive(list) (or, in fact, any other call like Console.WriteLine(list)) at the very end of the method Main in order to keep this reference in memory during getting snapshot.

0

Its is clear for me now. Thanks for the prompt answer!

0

Please sign in to leave a comment.