简体   繁体   中英

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

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?

You can't control when C# actually frees its memory. Once you've Clear ed 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM