Monitoring the garbage collector

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.

Comments (4)

  1. zman says:

    I saw someone do a similar trick using a Finalizer once. Of course the Finalizer is running in a separate thread so it oo is not 100% accurate about time.

  2. JoelMartinez says:

    So did you find anything? 😛

  3. ShawnHargreaves says:

    > So did you find anything? 😛


  4. XeviaN says:

    Garbaging seems to be proportional to the string size. Zero sized string = no garbage. Long string = frequent gc action.  🙂

Skip to main content