title: Commons Lang StringUtils.replace performance vs String.replace
body: <p>When I compared performance of Apache's <code>StringUtils.replace()</code> vs <code>String.replace()</code> I was surprised to know that the former is about 4 times faster. I used Google's Caliper framework to measure performance. Here's my test </p>
  
  <pre><code>public class Performance extends SimpleBenchmark {
      String s = "111222111222";
  
      public int timeM1(int n) {
          int res = 0;
          for (int x = 0; x &lt; n; x++) {
              res += s.replace("111", "333").length();
          }
          return res;
      }
  
      public int timeM2(int n) {
          int res = 0;
          for (int x = 0; x &lt; n; x++) {
              res += StringUtils.replace(s, "111", "333", -1).length();
          }
          return res;
      }
  
      public static void main(String... args) {
          Runner.main(Performance.class, args);
      }
  }
  </code></pre>
  
  <p>output</p>
  
  <pre><code> 0% Scenario{vm=java, trial=0, benchmark=M1} 9820,93 ns; ?=1053,91 ns @ 10 trials
  50% Scenario{vm=java, trial=0, benchmark=M2} 2594,67 ns; ?=58,12 ns @ 10 trials
  
  benchmark   us linear runtime
         M1 9,82 ==============================
         M2 2,59 =======
  </code></pre>
  
  <p>Why is that? Both methods seem to do the same work, <code>StringUtils.replace()</code> is even more flexible.</p>