Раньше я думал, что String.replace быстрее, чем String.replaceAll, потому что последнее использует регулярное выражение Pattern, а первое - нет. Но на самом деле нет существенных различий ни в производительности, ни в реализации. Это он:
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
Что нужно использовать здесь? Я написал версию замены без регулярного выражения
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();
}
и сравнили производительность
public static void main(String args[]) throws Exception {
String s1 = "11112233211";
for (;;) {
long t0 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
// String s2 = s1.replace("11", "xxx");
String s2 = replace(s1, "11", "22");
}
System.out.println(System.currentTimeMillis() - t0);
}
}
Тесты: моя версия - 400ms
; Версия JDK - 1700ms
.
Является ли мой тест неправильным или String.replace действительно неэффективен?