DimkaNewtown Posted November 15, 2005 Posted November 15, 2005 Here's my situation, I have a collection of objects which have collections of objects several levels deep. When I am done working with these objects I call .Clear() method on the topmost object. MSDN2 states that this method will clear the collection and release object members for garbage collection. Does this mean that it's recursive and child collections will also be released or will the subsequent children still be alive and kicking in memory? In pseudocode it would look someething like this (assume all members are exposed correctly): [csharp] class A { Collection<B> _b; } class B { Collection<C> _c; } class C { somevar = 1; } main { Collection<A> collA = new Collection<A>(); //load collection and its children, do processing //time to unload collA.Clear(); } [/csharp] Would that work fine or do I need to go through each child collection manually clearing it? [csharp] main { Collection<A> collA = new Collection<A>(); //load collection and its children, do processing //time to unload collA.B.C.Clear(); collA.B.Clear(); collA.Clear(); } [/csharp] My concern are the dangling objects which won't be picked up by the garbage collector until far far later. Quote
Leaders snarfblam Posted November 16, 2005 Leaders Posted November 16, 2005 The garbage collection works by reference tracing. It starts with "roots" (for example, a UI element, namely a form, would be a root since the user can interact with it and raise events or trigger function calls), and traces all the references. Any isolated objects (objects that do not have any delegates or references pointing to them, and therefore can not possibly interact with any other code or UI) or isolated groups of objects are collected. When you release an entire collection, as long as nothing else (that can be traced to from a root) has a reference to the items in the collection, they are available for garbage collection. Quote [sIGPIC]e[/sIGPIC]
DimkaNewtown Posted November 16, 2005 Author Posted November 16, 2005 Would it help to explicitely destroy (or at least dereference by setting to null) large child objects of the collection to facilitate faster memory reclamation or is it just a waste of time and code? Quote
Administrators PlausiblyDamp Posted November 16, 2005 Administrators Posted November 16, 2005 If the collection is going to go out of scope then I would just leave it to the GC entirely, otherwise setting the variable to null will allow the GC to collect it the next time it kicks in. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.