Disposing and GC

January 29, 2011
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:
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
 

Index Loops vs For Each

January 29, 2011
For Each loops are bad, mmmKay?
I avoid them for 2 main reasons:

1. Index loops are faster.
2. You cant modify a list inside a For Each loop.

I'll explain.
This will fail at the remove call:
For Each str As String In lstStr
     'test for something
     If str = "boosh"
          lstStr.Remove(str)
     End If
Loop
It fails because you have changed the list count and therefor the index.

This however, will work:
For i As Integer = lstStr.Count -1 To 0 Step -1
     'test for something
     If lstSt...

Continue reading...
 

Categories

Recent Posts