Hi David,
If the variable is going out of scope, eg it's a local variable or within
a for loop, etc, then there is no advantage in setting it to Nothing. In fact
it may be disadvantageous.
David Notario from the Microsoft JIT compiler team was discussing this
issue. He was adamant that setting variables to Nothing was generally a <bad>
idea within local scope as it upset the compiler's ability to optimise garbage
collection. In the normal case the compiler knows where you last <use> a
variable. At that point it can make the variable available for garbage
collection. If you have an assignment of Nothing then this moves the last-use
position further down in the code and this could mean that the variable hangs
around. But then it's common to set to Nothing just after calling Close,
Dispose or Quit, so that wouldn't make any difference. But David also said
that if the last thing you do with a variable is set it to Nothing, the
compiler will optimise the assignment away.
In this example:
Sub Foo (oSomethingVeryLarge As SomeType)
DoSomethingWith (oSomethingVeryLarge)
oSomethingVeryLarge = Nothing 'Irrelevant!!
DoSomethingLongRunning
End Sub
It seems sensible to set oSomethingVeryLarge to Nothing so that the GC can
collect the memory while SomethingLongRunning is taking place. In fact the
compiler removes the assignment.
But that means, you cry in alarm, that the reference to the memory is
still there and the garbage collector won't collect it. Not so, says David,
reassuringly. The compiler knows that oSomethingVeryLarge is not used after
DoSomethingWith() and makes it available for collection <at that point>
automatically - regardless of the assignment to Nothing.
That's local scope. - a lot of words to say don't bother with Nothing.
If it's a long-term scope variable, however, (eg in a Module or an object
that has a long lifetime), then once that particular variable is no longer of
use, set it to Nothing at the earliest opportunity.
The most important thing to remember is that you use Close or Dispose
whenever an object has them. If you fail to do your closing and disposing then
the resources used by your object will be retained until the garbage collector
calls the object's Finalize. This may take some time. And it's not guaranteed.
Regards,
Fergus
==============================
<quote> In general, I would STRONGLY recommend against nulling out locals
</quote>
David Notario,
Software Design Engineer - CLR JIT Compiler
The full discussion in [microsoft.public.dotnet.framework.performance] about
whether to set variables to Nothing.
via:
http://tinyurl.com/ouof