Monitoring the garbage collector

Originally posted to Shawn Hargreaves Blog on MSDN, Friday, October 12, 2007

We heard rumors that SpriteBatch.DrawString was generating garbage on Xbox, so this morning I set out to investigate and fix the issue. Trouble is, the Xbox Remote Performance Monitor tool isn't working with my interim build of the framework. How can I possibly investigate or confirm a fix to a GC issue, without access to any GC monitoring tools?

I was determined to tackle this bug now, rather than deferring it until after the RPM tool gets fixed. Here's what I came up with:

    WeakReference gcTracker = new WeakReference(new object());

and in my Update method:

    if (!gcTracker.IsAlive)
    {
        Trace.WriteLine("A garbage collection occurred!");
        gcTracker = new WeakReference(new object());
    }

This isn't perfect (for instance it cannot tell if multiple collections happen between one update and the next), but it was more than sufficient to answer simple questions like "is the collector ever running?" or "is it running ridiculously often?".

This mechanism is lightweight enough that games could feasibly use it to display a GCPS statistic next to their FPS counter.

Blog index   -   Back to my homepage