posted on Sunday, April 03, 2005 12:40 PM
by
johnwood
Garbage Collection Quiz?
John Papa posted a quiz about garbage collection, but I'm not sure I agree / understand... perhaps he could back it up with an example?
He claims that, when running the following code:
public void foo()
{
Class1 x = new Class1();
Class2 y = new Class2();
y.Width = x.GetWidth();
y.Height = y.Width;
y.Color = "Red";
}
... x becomes eligible for collection right after the call to GetWidth, because it's not used in the rest of the method. While I think that would be cool if possible, that's a kind of undeterministic finalization from hell -- what if that's a GDI object like a window, and it just disappears because you don't use it in the rest of the function, when you expect it to be there? What about the overhead of the JITter having to determine this - is it really worth it? Can i turn it off?
However when I tested this out, with the following code, I can't see that it's right. It doesn't get marked for collection after that call according to my tests.
class Class2 : Class1 { }
class Class1
{
public int Width;
public int Height;
public string Color;
public int GetWidth( )
{
return Width;
}
~Class1( )
{
Console.WriteLine( "Destructor for " + this.GetType( ) .Name) ;
}
public static void foo( )
{
Class1 x = new Class1( ) ;
Class2 y = new Class2( ) ;
y.Width = x.GetWidth( ) ;
// Console.WriteLine( "Collecting") ; GC.Collect( ) ; // #1
y.Height = y.Width;
y.Color = "Red";
}
static void Main( string[ ] args)
{
foo( ) ;
// Console.WriteLine( "Collecting") ; GC.Collect( ) ; // #2
Console.ReadLine( ) ;
}
}
If I run this with #2 uncommented, then both classes get destroyed at the uncommented line, as expected.
If I recomment #2 and uncomment #1, then I just get “Collecting” and no finalizing takes place.
Maybe I'm missing something... so as I said.. I'd like to see an example that demonstrates it.
It turns out that this *is* the case, but only outside of a debugger. There's a great article about this here:
http://mtaulty.com/blog/archive/2005/02/17/1496.aspx
I've definitely learnt something here!