3

I have the following nested dictionaries:

  1. Dictionary<int, Dictionary<string, object>> x;
  2. Dictionary<int, SortedDictionary<long, Dictionary<string, object>>> y;

If I do x.Clear() and y.Clear() will all the nested objects clear and all the memory will be reused on the next garbage collection?

Or do I need to iterate on all the items and clear them manually?

1
  • Watch out for objects that implement IDisposable. Mar 31, 2010 at 12:57

3 Answers 3

4

If none of your objects are reachable from other parts of your code, they will all be garbage collected.

If this will be done on the next garbage collection, depends on the generation that they belong to.

This article from Jeffrey Richter explains a lot.

1
  • Of course determining this could be the hard part, but in essence this is how GC works. Mar 31, 2010 at 12:46
0

It's the same for everything: the GC starts from its roots (variables on the stack and various other odd cases) and walks the tree of reachable objects by following references. Any objects not found by that process will be eligible for collection.

So as long as your removed sub-dictionaries are not reachable some other way, they will be collected.

0

Maybe yes.

If you have references to items in the dictionary, regardless of the type of the value parameter, than those objects won't be collected.

But if there are no references, then they will be collected (at some point).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.