title: Inverse String.Replace - Faster way of doing it?
body: <p>I have a method to replace every character except those I specify. For example, </p>
  
  <pre><code>ReplaceNot("test. stop; or, not", ".;/\\".ToCharArray(), '*'); 
  </code></pre>
  
  <p>would return </p>
  
  <pre>
  "****.*****;***,****".
  </pre>
  
  <p>Now, this is not an instance of premature optimization. I call this method quite a few times during a network operation. I found that on longer strings, it is causing some latency, and removing it helped a bit. Any help to speed this up would be appreciated.</p>
  
  <pre><code>    public static string ReplaceNot(this string original, char[] pattern, char replacement)
      {           
          int index = 0;
          int old = -1;
  
          StringBuilder sb = new StringBuilder(original.Length);
  
          while ((index = original.IndexOfAny(pattern, index)) &gt; -1)
          {
              sb.Append(new string(replacement, index - old - 1));
              sb.Append(original[index]);
              old = index++;
          }
  
          if (original.Length - old &gt; 1)
          {
              sb.Append(new string(replacement, original.Length - (old + 1)));
          }
  
          return sb.ToString();
      }
  </code></pre>
  
  <p>Final #'s. I also added a test case for a 3K character string, ran at 100K times instead of 1M to see how well each of these scales. The only surprise was that the regular expression 'scaled better' than the others, but it is no help since it is very slow to begin with:</p>
  
  <pre>
  User            Short * 1M  Long * 100K     Scale
  John            319             2125            6.66
  Luke            360             2659            7.39
  Guffa           409             2827            6.91
  Mine            447             3372            7.54
  DirkGently      1094            9134            8.35
  Michael         1591            12785           8.04
  Peter           21106           94386           4.47
  </pre>
  
  <p>Update: I made the creation of the regular expression for Peter's version a static variable, and set it to RegexOptions.Compiled to be fair:</p>
  
  <pre>
  User            Short * 1M      Long * 100K     Scale
  Peter           8997            74715           8.30
  </pre>
  
  <p>Pastebin link to my testing code, please correct me if it is wrong:
   <a href="http://pastebin.com/f64f260ee" rel="nofollow noreferrer"><a href="http://pastebin.com/f64f260ee" rel="nofollow noreferrer">http://pastebin.com/f64f260ee</a></a></p>