Why this object does not collect garbage

In the next code segment, I wonder why testvectorsit isn’t going to after the function call. I see that memory usage is increased to 270 MB, and then stays there forever.

This function is called directly from Main.

private static void increaseMemoryUsage()
{
    List<List<float>> testvectors = new List<List<float>>();
    int vectorNum = 250 * 250;
    Random rand = new Random();

    for (int i = 0; i < vectorNum; i++)
    {
        List<Single> vec = new List<Single>();

        for (int j = 0; j < 1000; j++)
                {
            vec.Add((Single)rand.NextDouble());
        }
        testvectors.Add(vec);
    }
}
+5
source share
6 answers

Do not confuse garbage collection with reference counting. Memory is freed when the runtime decides, and not always when it is no longer referenced. Quote:

Garbage collection occurs when one of the following conditions is true: true:

The system has low physical memory.

, . , . .

GC.Collect. , . .

, :

http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx

+9

GC , . . , . Gen2.

, , , .

GC GC.Collect(), .

+5

, :

 class Program
    {
        static void Main(string[] args)
        {
            increaseMemoryUsage();

            Console.WriteLine("Hit enter to force GC");
            Console.ReadLine();

            GC.Collect();

            Console.ReadLine();
        }

        private static void increaseMemoryUsage()
        {
            var testvectors = new List<List<float>>();
            const int vectorNum = 250 * 250;
            var rand = new Random();

            for (var i = 0; i < vectorNum; i++)
            {
                var vec = new List<Single>();

                for (var j = 0; j < 1000; j++)
                    vec.Add((Single)rand.NextDouble());

                testvectors.Add(vec);
            }
        }    
    }
+3

Most likely, your test vectors get upgraded to a heap of large objects (LOH), and then they are not collected during the Gen0 collection.

Good link here .

0
source

Garbage collection is not deterministic. It is up to the GC to decide when this is a good moment to do it.

0
source

Try adding GC.GetTotalMemory (true) before and after increasing the use of the MemoryUsage () method and compare the numbers.

0
source

All Articles