Disposing and GC
Posted by Jessie Burns on Saturday, January 29, 2011
Under: Efficiency
Okay, I know that no one really knows or understands the GC. I still want to touch on it briefly here.
Some people tend to go too far when trying to prevent or cleanup memory leaks. If you remember 2 simple rules, it will save you a lot of headache.
1. Dispose of it when your done with it. The Using statement is my favorite way to accomplish this.
2. Make sure any pointers back to it are set to Nothing.
Do this and the GC will do it's job and you wont have to over-engineer destroying everything.
An example would maybe be with a list:
lstCustom.Clear only takes the objects out of the list. The objects still exist though. Even though there arent any pointers to the objects, there's really no telling how long they will be floating around before the GC picks em up. The way I like to handle this is to destroy the objects first, then remove them. Like so:
Some people tend to go too far when trying to prevent or cleanup memory leaks. If you remember 2 simple rules, it will save you a lot of headache.
1. Dispose of it when your done with it. The Using statement is my favorite way to accomplish this.
2. Make sure any pointers back to it are set to Nothing.
Do this and the GC will do it's job and you wont have to over-engineer destroying everything.
An example would maybe be with a list:
Dim lstCustom As New List(Of MyCustomClass) 'or whatever you want to put in it.
For i As Integer = 0 to 10
lstCustom.Add(New MyCustomClass(i))
Next
'...do some stuff then clear the list
lstCustom.Clear 'this is (imho) a mistake
lstCustom.Clear only takes the objects out of the list. The objects still exist though. Even though there arent any pointers to the objects, there's really no telling how long they will be floating around before the GC picks em up. The way I like to handle this is to destroy the objects first, then remove them. Like so:
For i As Integer = lstCustom.Count -1 to 0 Step -1
lstCustom(i).Dispose 'naturally this is only good on objects that implement IDisposable
lstCustom(i) = Nothing 'this would handle non-disposable objects
lstCustom.RemoveAt(i) 'you could do this or just wait til after the loop then call .Clear
Next
In : Efficiency