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, you will not create garbage, and it’s fast, so that’s perfectly okay.
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();