GC Myth is Real

2/20/2004 6:53:11 PM

GC Myth is Real

Paul Wilson points out a Garbage College myth, "Set Object to Null," that he tries to dispel, but he is only half right. The myth is:

There is never any reason to set your objects to null since the garbage collection will do this for you automatically.

He asserts that there are times where setting objects to null can make huge differences in the memory footprint of the application. This is true; there are times. However, he also implies that references, which are not nulled out, will only be collected after the reference goes out of scope. This is not true.

The garbage collector does, in fact, track the last known use of a variable within a method, and will upon collection, ignore those variables, whose instruction pointer exceeds the address of the last known use of those variable.If a variable is still used further down a function, then setting object to null does help.

Let me point out System.GC.KeepAlive(obj), a function call that is used to prevent objects from being freed prematurely. In the following example from Rotor, the GC can prematurely close the stream before MethodThatSpansGC() finishes. This is because the Foo object is no longer used in Main and the this pointer is no longer used when stream.MethodThatSpansGC is called.

class Foo { 
   Stream stream = ...; 
   protected void Finalize() { stream.Close(); } 
   void Problem() { stream.MethodThatSpansGCs(); } 
   static void Main() { new Foo().Problem(); } 

Adding GC.KeepAlive at the end of Problem() prevents the stream from being prematurely closed.






Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media