[NEW BUG]: Avoid allocations in String.replace(CharSequence, CharSequence) in case no replacement happened

Christoph Dreis christoph.dreis at freenet.de
Wed Mar 1 21:34:48 UTC 2017


I just noticed a small improvement for String.replace(CharSequence,
CharSequence) in case the target sequence is not found.

There is the possibility of an early-out in case there is nothing to
replace. Yet there is a call to replacement.toString();
While this is usually not a problem in case of String parameters, a
StringBuilder - or other more "dynamic" CharSequence.toString()
implementations - will likely produce unnecessary allocations here.

I think the JDK could prevent that with the given patch below.

I would be very happy if this is sponsored for JDK 10. 


===== PATCH ======
diff --git a/src/java.base/share/classes/java/lang/String.java
--- a/src/java.base/share/classes/java/lang/String.java
+++ b/src/java.base/share/classes/java/lang/String.java
@@ -2177,11 +2177,11 @@
     public String replace(CharSequence target, CharSequence replacement) {
         String tgtStr = target.toString();
-        String replStr = replacement.toString();
         int j = indexOf(tgtStr);
         if (j < 0) {
             return this;
+        String replStr = replacement.toString();
         int tgtLen = tgtStr.length();
         int tgtLen1 = Math.max(tgtLen, 1);
         int thisLen = length();

More information about the core-libs-dev mailing list