Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any benefit to nulling references to "encourage" .NET garbage collection?

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?

like image 999
H2ONaCl Avatar asked Aug 23 '10 17:08

H2ONaCl


3 Answers

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

  • http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx

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.

like image 129
JaredPar Avatar answered Nov 16 '22 01:11

JaredPar


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.

like image 28
Mark Avatar answered Nov 16 '22 02:11

Mark


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.

like image 2
Pat Avatar answered Nov 16 '22 01:11

Pat