Foreach through non-primitive types creates garbage.

Time and again I have seen code like this used in XNA tutorials.

effectDrawBlock.Begin();
foreach (EffectPass pass in effectDrawBlock.CurrentTechnique.Passes)
{
    pass.Begin(); 

    gd.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 35, 0, 70); 

    pass.End();
}
effectDrawBlock.End();

When you use a foreach over an array of ints (or any value type), no garbage is generated, it’s fast, readable, and often preferable to a for loop.

However, in the above code, “EffectPass pass in” creates a managed effect pass object, used to iterate through the collection. That object then needs to be handled by the garbage collector later.

The fix is to use a for loop when iterating over non-primitive types.
In my case, by changing my code to something more like what you see below, I was able to reduce the number of managed objects generated by my code from 2500/sec to 200/sec as measured by the XNA Framework Remote Perf Monitor.

effectDrawBlock.Begin();
for (int i = 0; i < effectDrawBlock.CurrentTechnique.Passes.Count; i++)
{
    effectDrawBlock.CurrentTechnique.Passes[i].Begin();

    gd.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 35, 0, 70);

    effectDrawBlock.CurrentTechnique.Passes[i].End();
}
effectDrawBlock.End();
This entry was posted in Coding, XNA and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>