Memory management with collections

UncleRonin

Well-known member
Joined
Feb 28, 2006
Messages
230
Location
South Africa
Programming Experience
5-10
Say for example there is a Class with a member in the form of List(Of Object) and you populate it with a bunch of stuff. Now you wanna get rid of the items so you call ListVariable.Clear and then everything supposedly vanishes.

What really happens to the list items? Does the ListVariable simply dereference the items and then the GC gobbles them up later or does the ListVariable call Dispose on all the items?

Or say you have a List(Of Object) with a bunch of stuff and then you reinitialise the variable by saying ListVariable = New List(Of Object) right away.

What happens to the old list and its items?

I've done some searching and checked around and I've noticed quite a few people going wild and calling ListVariable.Clear, ListVariable.Dispose and then finishing with a flourish and using ListVariable = Nothing. Then they initialise it by calling the contructor.

Now, obviously the use of all of this depends on the circumstances but in General is it actually necessary to go to do the full number of steps above or would calling the constructor do the trick alone? I'm guessing that just that one step calling the contructor will dereference the old list and then the GC would get super excited and gobble it all up...

But as far as processing goes, would the full number of steps save processing for the GC and instead do the processing in the application and be faster overall? Or would it be faster to just dereference it and let the GC do the processing itself and that be faster overall? Or does it not matter either way since the processing taking place will be the same anyways?

I don't know where the line between managed and unmanaged resources would be but assume that all resources are managed... (I think? :eek:)
 
Remove/Clear will just remove, if the objects need disposal you must do that first. Same with replacing an object in the list, the old item is just dereferenced, you must Dispose it first if that class object requires it.
 
Back
Top