title: String.Where Comparatively Poor Performance
body: <p>I have two methods that take a string and remove any 'invalid' characters (characters contained in a hashset). One method uses Linq.Where, another uses a loop w/ char array. </p>
  
  <p>The Linq method takes nearly twice as long (208756.9 ticks) as the loop (108688.2 ticks)</p>
  
  <p>Linq:</p>
  
  <pre><code>    string Linq(string field)
      {
          var c = field.Where(p =&gt; !hashChar.Contains(p));
          return new string(c.ToArray());
      }
  </code></pre>
  
  <p>Loop: </p>
  
  <pre><code>    string CharArray(string field)
      {
          char[] c = new char[field.Length];
          int count = 0;
  
          for (int i = 0; i &lt; field.Length; i++)
              if (!hashChar.Contains(field[i]))
              {
                  c[count] = field[i];
                  count++;
              }
  
          if (count == 0)
              return field;
  
          char[] f = new char[count];
  
          Buffer.BlockCopy(c, 0, f, 0, count * sizeof(char));
  
          return new string(f);
      }
  </code></pre>
  
  <p>My expectation would be that LINQ would beat, or at least be comparable to, the loop method. The loop method isn't even optimized. I must be missing something here. </p>
  
  <p>How does Linq.Where work under the hood, and why does it lose to my method?</p>