When I compared performance of Apache's StringUtils.replace()
vs String.replace()
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
public class Performance extends SimpleBenchmark {
String s = "111222111222";
public int timeM1(int n) {
int res = 0;
for (int x = 0; x < n; x++) {
res += s.replace("111", "333").length();
}
return res;
}
public int timeM2(int n) {
int res = 0;
for (int x = 0; x < n; x++) {
res += StringUtils.replace(s, "111", "333", -1).length();
}
return res;
}
public static void main(String... args) {
Runner.main(Performance.class, args);
}
}
output
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 =======
Why is that? Both methods seem to do the same work, StringUtils.replace()
is even more flexible.