Search code examples
c#memorygarbage-collectioncontainers

Efficient way to Delete Data-Structures and Release Memory in C# (Garbage Collection)


Imagine a data structure consisting of several nested (standard) containers, like below.

Example:

var data = new Dictionary<int, HashSet<float>>()
{
    {
        0, new HashSet<float>() { 1F, 2F, }
    },
    {
        1, new HashSet<float>() { 3F, 4F, }
    },
};

data.Remove(0);

What is the correct way to fully delete one value of the top level Dictionary (including the nested elements inside the HashSet)? The memory should be freed and no leaks should be possible.

Is data.Remove(0) as simple as it is the best way, because the garbage collection does everything automatically?


Solution

  • It makes no difference. The garbage collector is the ONLY way to release memory. IDisposable is only there to allow objects (which survive the call to it) to release unmanaged ressources (which can be unmanaged memory, file handles etc.), it has no impact on managed memory.

    In fact, modern C# 8 nullable/non nullable reference types actually get in the way of "just" setting variables to null in dispoable anyway.

    Deleting all keys of a dictionary will not release any memory and you have to anyway wait for the garbage collector.