I'm developing an Xbox 360 game with XNA. I'd really like to use C#'s yield return construct in a couple of places, but it seems to create a lot of garbage. Have a look at this code:
class ComponentPool<T> where T : DrawableGameComponent { List<T> preallocatedComponents; public IEnumerable<T> Components { get { foreach (T component in this.preallocatedComponents) { // Enabled often changes during iteration over Components // for example, it's not uncommon for bullet components to get // disabled during collision testing // sorry I didn't make that clear originally if (component.Enabled) { yield return component; } } } } ... I use these component pools everywhere - for bullets, enemies, explosions; anything numerous and transient. I often need to loop over their contents, and I'm only ever interested in components that are active (i.e., Enabled == true), hence the behavior of the Components property.
Currently, I'm seeing as much as ~800K per second of additional garbage when using this technique. Is this avoidable? Is there another way to use yield return?
Edit: I found this question about the broader issue of how to iterate over a resource pool without creating garbage. A lot of commenters were dismissive, apparently not understanding the limitations of the Compact Framework, but this commenter was more sympathetic and suggested creating an iterator pool. That's the solution I'm going to use.
yield returnis the culprit. Likely the culprit is in creating the iterator. Every time you call this, an iterator is allocated. But since it's short-lived (i.e. Gen 0), it shouldn't be a problem. Are you noticing a performance problem?yield returnin this particular case? You should be able to write something likereturn preallocatedComponents.Where( c => c.Enabled );, which is cleaner and shorter.