title: C#'s `yield return` is creating a lot of garbage for me. Can it be helped?
body: <p>I'm developing an Xbox 360 game with XNA. I'd <em>really</em> like to use C#'s <code>yield return</code> construct in a couple of places, but it seems to create a lot of garbage. Have a look at this code:</p>
  
  <pre><code>class ComponentPool&lt;T&gt; where T : DrawableGameComponent
      {
      List&lt;T&gt; preallocatedComponents;
  
      public IEnumerable&lt;T&gt; 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;
                      }
                  }
              }
          }
      ...
  </code></pre>
  
  <p>I use these component pools <em>everywhere</em> - 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., <code>Enabled == true</code>), hence the behavior of the <code>Components</code> property.</p>
  
  <p>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 <code>yield return</code>?</p>
  
  <p>Edit: I found <a href="https://stackoverflow.com/questions/5486654/allowing-iteration-without-generating-any-garbage">this question</a> 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 <a href="https://stackoverflow.com/questions/5486654/allowing-iteration-without-generating-any-garbage/5488242#5488242">this commenter</a> was more sympathetic and suggested creating an iterator pool. That's the solution I'm going to use.</p>