Home > Net >  Why clearing the content of an object does not free memory?
Why clearing the content of an object does not free memory?

Time:12-04

What should I do when I have situations as the one below, where I'd need to clean an object and immediately free its allocated memory?

After creating a List<string> with 10 million words, process memory goes up to ~150MB.

List<string> list = new();
int length = 10000000;
for (int i = 0; i < length; i  )
{
    list.Add("test");
}

Console.ReadLine();
list.Clear();
Console.ReadLine();

Even though the list is cleared, I don't see memory being freed just after that. Could anyone give me some guidance on this, please?

CodePudding user response:

You can't control when C# actually frees its memory. Once you've Cleared a list all the items that used to be in it are eligible to be garbage-collected (assuming nothing else holds a reference to them, as in the given example), but you can't control when exactly C#'s garbage collector will actually free them.

CodePudding user response:

List.Clear just replaces all of the copies of references to each of the cleared strings with nulls. So the actual buffer in the list is exactly the same size, the values in it are all just zeros. Since the list was just full of references to a single string in the literal pool, none of the objects referenced by the list have become eligible for collection (the one object that used to be in the list is still alive because it's in the string intern pool, which is rooted).

To actually clear out the internal list buffer you'll either need to remove all references to the list itself, or set a smaller Capacity on the list to have a new, smaller, buffer created, allowing the old one to be collected.

  • Related