Suppose there is the following code:
foreach (...)
{
List<int> localList = new List<int>(100);
// do stuff
localList = null;
}
From time to time, I am tempted to null references just as the procedure is about to exit (that is, return) or in this case, just as it is about to loop. Is there any benefit to doing so, even if a small one?
There is no benefit to doing this for local variables. The CLR knows, by means of the JIT, exactly when a local variable is no longer used within a method and hence collectable.
Raymond Chen recently did a very in depth blog article on exactly when objects are collectible . It covers this scenario in detail and is worth the read
There is however a couple of exceptions to this rule. If the local variable in question is captured into a closure or an iterator then yes nulling out the variable has an effect. Namely because the local is no longer a local but instead is a field and has different GC semantics.
No. In fact, "nulling" local variables can, under some circumstances, prevent garbage collection. In normal operation, as soon as a variable is no longer reachable from any executing code, it becomes available for garbage collection. If, at the end of your method, you "null-out" the variable, you keep it "alive" until that moment, and actually delay it's availability for garbage collection.
Not if the declaration is within blocks like you have. Once it's out of scope the reference will be nullified automatically and GC'd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With