Is String.replace implementation really efficient?
<p>I used to think that String.replace is faster than String.replaceAll because the latter uses Pattern regex and the former does not. But in fact there is no significant difference either in performance or implementation. This is it:</p>

<pre><code>public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
        this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
</code></pre>

<p>What's the need to use Pattern here? I wrote a non-regex replace version</p>

<pre><code>static String replace(String s, String target, String replacement) {
    StringBuilder sb = new StringBuilder(s);
    for (int i = 0; (i = sb.indexOf(target, i)) != -1; i += replacement.length()) {
        sb.replace(i, i + target.length(), replacement);
    }
    return sb.toString();
}
</code></pre>

<p>and compared performance</p>

<pre><code>    public static void main(String args[]) throws Exception {
        String s1 = "11112233211";
        for (;;) {
            long t0 = System.currentTimeMillis();
            for (int i = 0; i &lt; 1000000; i++) {
//              String s2 = s1.replace("11", "xxx");
                 String s2 = replace(s1, "11", "22");
            }
            System.out.println(System.currentTimeMillis() - t0);
        }
    }
</code></pre>

<p>Benchmarks: my version - <code>400ms</code>; JDK version - <code>1700ms</code>. </p>

<p>Is my test wrong or is String.replace really inefficient?</p>
