Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collector test

I have written a simple .net forms application to test some behaviour of .NET about how it handles memory together with the garbage collector to do the cleaning.

The forms application GUI looks like this:

Application GUI

And the code behind like this:

public partial class Form1 : Form
{
    private readonly IList<byte[]> _btyList = new List<byte[]>();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < 3)
        {
            byte[] buffer = File.ReadAllBytes(@"C:\PFiles\20131018_nl_metro holland.pdf");
            _btyList.Add(buffer);
            i++;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < _btyList.Count)
        {
            _btyList[i] = null;
            i++;
        }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        GC.Collect();
    }
}

When I add a couple of byte arrays to the private list of byte arrays it (of course) has effect on the memory usage of the application:

Memory usage after adding byte arrays

Now when I press the Clear memory button the memory usage will stay the same. I can wait for hours, but it doesn't change. If I press the Garbage collect button (after Clear memory) it will free the memory immediately:

Memory usage after garbage collect

The question is: Why does the garbage collector not work in this case?

like image 850
Kees de Wit Avatar asked Dec 19 '22 22:12

Kees de Wit


2 Answers

The garbage collector isn't running because it doesn't need to. If memory is not low, there is no need to collect.

If you have 4GB of memory, 360MB is probably below the collection threshold.

You shouldn't, in general, ever worry or think about when the GC runs, unless you are writing time or memory critical code.

Ref.: Fundamentals of Garbage Collection

Understanding Garbage Collection in .NET

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

  • The system has low physical memory.

  • The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.

  • The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

like image 67
Mitch Wheat Avatar answered Dec 22 '22 12:12

Mitch Wheat


Garbage collection is relatively slow and the CLR won't do it every time memory becomes free, only when it needs to. So "freeing" your array doesn't trigger it.

Your experiment has been a complete success: you have learned something about how garbage collection works.

like image 44
David Arno Avatar answered Dec 22 '22 11:12

David Arno