Adding special handling of the case when this String and both arguments are Latin1 encoded shows significant performance improvement.
With the benchmark
public class StringReplace {
public String s = new String("java.lang.String");
@Benchmark
public String replace1_0() {
return s.replace(".", "");
}
@Benchmark
public String replace1_1() {
return s.replace(".", "/");
}
@Benchmark
public String replace1_2() {
return s.replace(".", "::");
}
}
the following numbers are observed:
prior fix:
Benchmark Mode Cnt Score Error Units
StringReplace.replace1_0 avgt 18 76.706 ± 2.124 ns/op
StringReplace.replace1_1 avgt 18 90.630 ± 4.680 ns/op
StringReplace.replace1_2 avgt 18 110.723 ± 12.093 ns/op
after fix:
Benchmark Mode Cnt Score Error Units
StringReplace.replace1_0 avgt 18 53.609 ± 0.478 ns/op
StringReplace.replace1_1 avgt 18 24.170 ± 0.214 ns/op
StringReplace.replace1_2 avgt 18 63.632 ± 0.648 ns/op
With the benchmark
public class StringReplace {
public String s = new String("java.lang.String");
@Benchmark
public String replace1_0() {
return s.replace(".", "");
}
@Benchmark
public String replace1_1() {
return s.replace(".", "/");
}
@Benchmark
public String replace1_2() {
return s.replace(".", "::");
}
}
the following numbers are observed:
prior fix:
Benchmark Mode Cnt Score Error Units
StringReplace.replace1_0 avgt 18 76.706 ± 2.124 ns/op
StringReplace.replace1_1 avgt 18 90.630 ± 4.680 ns/op
StringReplace.replace1_2 avgt 18 110.723 ± 12.093 ns/op
after fix:
Benchmark Mode Cnt Score Error Units
StringReplace.replace1_0 avgt 18 53.609 ± 0.478 ns/op
StringReplace.replace1_1 avgt 18 24.170 ± 0.214 ns/op
StringReplace.replace1_2 avgt 18 63.632 ± 0.648 ns/op
- relates to
-
JDK-8222806 Inefficient String.replace in PathFileObject.toBinaryName
- Open
-
JDK-8058779 Faster implementation of String.replace(CharSequence, CharSequence)
- Resolved