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 differenc
There is one interesting aspect when comparing the two solutions, at least on my machine. The built-in version scales much better when it comes to larger strings. Given a slightly modified version of your test:
for (int i = 0; i < 10; i++) {
s1 = s1 + s1;
long t0 = call1(s1); // your implementation
long t1 = call2(s1); // 1.7_07 Oracle
long delta = t0 - t1;
System.out.println(
String.format("Iteration %s, string length %s, call1 %s, call2 %s, delta %s", i, s1.length(), t0, t1, delta));
try {
Thread.sleep(200);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
By just doubling the string length with each call, the break-even is reached already after iteration 3 or 4:
Iteration 0, string length 22, call1 450, call2 1715, delta -1265
Iteration 1, string length 44, call1 1048, call2 2152, delta -1104
Iteration 2, string length 88, call1 2695, call2 4024, delta -1329
Iteration 3, string length 176, call1 7737, call2 7574, delta 163
Iteration 4, string length 352, call1 24662, call2 15560, delta 9102
For reference the two implementations of call1 and call2:
static long call1(String s) {
long t0 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s2 = replace(s, "11", "22");
}
return System.currentTimeMillis() - t0;
}
static long call2(String s) {
long t0 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s2 = s.replace("11", "xxx");
}
return System.currentTimeMillis() - t0;
}