.NET GC Myth #1 -- Set Object to Null
.NET Garbage Collection Myth #1:
There is never any reason to setting your objects to null (or nothing in VB) since the GC will do this for you automatically.
There are times where setting your objects to null (or nothing in VB) can make huge differences in your memory footprint.
Yes, you do not “need” to ever set an object to null since the GC will eventually collect your object after it goes out of scope. For small objects that have a short life this is great, and its exactly why GC is a great thing. But there are exceptions, and the experts aren't helping by ignoring these cases by simply making blanket statements. I have an example you can download and try for yourself, as well as several charts from the example, that illustrates one of these cases -- see my last post for more details. This particular case involves a large object that is replaced by another large object, which leaves you vulnerable to having two such large objects in memory if you don't first set the existing object to null. Why? Mostly because the first large object never goes out of scope until it is replaced by the second, so the GC doesn't know you're done with it early enough. I've had some very well informed people tell me that setting the object to null in the middle of a method is meaningless -- and I believed them after hearing it so many times -- that is until I saw it for myself, thanks to Doug Ware of Magenic. My sample app also calls the Clear method, and Dispose when its defined, but actually my more detailed tests showed they did not make any difference, but the set to null made a huge difference. Now some people have told me this example is flawed because you could design the app in such a way so that the first large object could go out of scope before creating the second large object. This criticism is partially valid -- my example was concocted to show the worst case, which I also don't think is all that uncommon in many winform applications with datagrids. But I also had an earlier version of the example which did have this other design, and it also showed a significantly smaller average memory footprint when the objects were set to null, although not as drastic as the example noted above. So what's my point? Just that while you may not “need” to set your objects to null, there are some cases where you can realize significant gains by being preemptive and setting your large objects to null when you know they are no longer needed.