Does Garbage Collector Collect This Code?

Hi all,

I was wondering if I do this type of code, does the garbage collector clear the memory?

Dictionary<string, string> CurrentLanguage = new Dictionary<string, string>();

    public void ChangeLanguage(SystemLanguage newLanguage)
    {
        CurrentLanguage = new Dictionary<string, string>();

        //... Fill the dictionary from a file
    }

The player can change the language so often if they want. So that, if I create a new Dictionary whenever ChangeLanguage function is called, does the garbage collector clear the old Dictionary from the memory?

If this dictionary isnt referenced anywhere else, then it will be collected sooner or later.

yes, because you auto-dereference the variable when you assign a new reference to it.

meaning that the old dictionary isn’t referenced by anything and is from that point on in a limbo, waiting to be collected.
this is not a particularly efficient way of doing disposal.

you typically want to reuse an object, not only to avoid this behavior, but also because it’s less likely to introduce memory fragmentation that will surely slow down GC at some point in the future.

use CurrentLanguage.Clear();
instead of CurrentLanguage = new Dictionary<…>()

it also helps to suggest dictionary’s capacity in the constructor if you’re doing this frequently.
it will allocate the memory more efficiently, which may slightly impact its running performance as well as avoid needless memory fragmentation.

you also don’t have to avoid auto-dereferencing at all costs. if you do this only seldomly, it’s perfectly fine.

I thought if I use Clear function, it will iterate the whole dictionary to reset the variables (give default values to them). Good to know, thank you!

it won’t, Clear is not O(n) but practically O(1) because in all honesty it also just dereferences, but might do it in a more memory-friendly manner due to internal implementation specifics. there are no guarantees however, but still you’re avoiding allocation of a completely new object.