Doug Reilly's Weblog

Embedded Reporting of the Information Age...

Another reason not to deploy Debug code...

In the CLR Internals class today, Jeff Richter gave a great deal of really good information.  One thing that I should have figured, but did not really know was about the impact of running Debug code on Garbage Collector performance.  Say you have code like this:

public void foo()
{
   BigOb big;
   big=new BigOb();
   System.Console.WriteLine("Big is Really big! {0} ",big.GetSize());
   // 1.
   LongSlowOperation();
   // 2.
}

The C++ programmer in me says that big will be in scope until just after the curly brace below the comment 2.  Turns out that in release mode, the big object will be available for garbage collection at the 1 comment (because the framework can tell that it is not referenced again in the code) unless the code is debug code.  In that case, the object will be available and not garbage colected as a convenience for you while debugging.  In most cases the difference may not be critical, but it just might in some cases.

Consider yourself warned<g>.

Comments

Graeme Foster said:

That's what the GC.KeepAlive method is for. If you insert GC.KeepAlive(big) at //2 the object won't be collected until execution reaces that point.
# October 27, 2003 8:07 AM

Douglas Reilly said:

True, but my point is, while I would expect biig to be in scope, it is just as well it can be GC'ed after the last reference, and so using debug code prevents that.
# October 27, 2003 5:53 PM

One of those VB Guys said:

What if, after //2 I were to add a line that said "Big = Nothing"? (Remember, I'm a VB guy) Would the framework still make "big" eligible for collection since it isn't "used", or would it hold on to it because of the last statement?

Thanks!
# October 29, 2003 7:36 AM

doug reilly said:

i believe it would not be available for gc until after you set it to null.
# October 29, 2003 11:20 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)