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.

4 Responses to Foreach through non-primitive types creates garbage.

  1. ugg Vest Women: cheap ugg, cheap ugg cheap Ugg presents the new collection and the Official Store Directly to buy online.
    ugg boots uk quality 353 http://realestateapprentice.ca/?p=ugg-boots-uk-quality-353.html

  2. おっと!私の古いもののような|このブログのただ正確にルックス!別のそれは、完全に完全に完全に上にあるトピックが、それはほとんど同じページレイアウトがあり、デザインが。 優秀色の選択!

  3. Every app or maybe software program possesses the benefits as well as crons therefore it is absolutely drastically wrong sighting the particular undesirable details about it. It includes a lot of the fine details and since the moment goes by these kind of faults will likely be soughted available. . -= GadgetGuide4U’s continue website… Google App For Google android is already Avaiable =-.

  4. 脸部瘦脸针
    北京最好的整形医院 http://wfsh.org/

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>