title: Performance between Iterating through IEnumerable<T> and List<T>
body: <p>Today, I faced a problem with performance while iterating through a list of items. After done some diagnostic, I finally figured out the reason which slowed down performance. It turned out that iterating through an <code>IEnumerable&lt;T&gt;</code> took much more time than iterating through a <code>List&lt;T&gt;</code>. Please help me understand why <code>IEnumerable&lt;T&gt;</code> is slower than <code>List&lt;T&gt;</code>.</p>
  
  <p><strong>UPDATE</strong> benchmark context:</p>
  
  <p>I'm using NHibernate to fetch a collection of items from a database into an <code>IEnumerable&lt;T&gt;</code> and sum its property's value. This is just a simple entity without any reference type:</p>
  
  <pre><code>public SimpleEntity
  {
      public int Id {get;set}
      public string Name {get;set}
      public decimal Price {get;set}
  }
  
  Public Test
  {
      void Main()
      {
          //this query get a list of about 200 items
          IEnumerable&lt;SimpleEntity&gt; entities = from entity in Session.Query&lt;SimpleEntity&gt;
                                               select entity;
  
          decimal value = 0.0;
          foreach(SimpleEntity item in entities)
          {
               //this for loop took 1.5 seconds 
               value += item.Price;
          }
  
          List&lt;SimpleEntity&gt; lstEntities = entities.ToList();
  
          foreach(SimpleEntity item in lstEntities)
          {
               //this for loop took less than a milisecond
               value += item.Price;
          }
      }
  }
  </code></pre>