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.