changeset 59807:20d92fe3ac52

8247605: Avoid array allocation when concatenating with empty string Reviewed-by: redestad, plevart
author tvaleev
date Tue, 16 Jun 2020 03:16:41 +0000
parents f86238fb05b6
children 616dd4cb9804
files src/java.base/share/classes/java/lang/StringConcatHelper.java test/micro/org/openjdk/bench/java/lang/StringConcat.java
diffstat 2 files changed, 20 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/src/java.base/share/classes/java/lang/StringConcatHelper.java	Tue Jun 16 04:20:30 2020 +0200
+++ b/src/java.base/share/classes/java/lang/StringConcatHelper.java	Tue Jun 16 03:16:41 2020 +0000
@@ -406,6 +406,14 @@
     static String simpleConcat(Object first, Object second) {
         String s1 = stringOf(first);
         String s2 = stringOf(second);
+        if (s1.isEmpty()) {
+            // newly created string required, see JLS 15.18.1
+            return new String(s2);
+        }
+        if (s2.isEmpty()) {
+            // newly created string required, see JLS 15.18.1
+            return new String(s1);
+        }
         // start "mixing" in length and coder or arguments, order is not
         // important
         long indexCoder = mix(initialCoder(), s1);
--- a/test/micro/org/openjdk/bench/java/lang/StringConcat.java	Tue Jun 16 04:20:30 2020 +0200
+++ b/test/micro/org/openjdk/bench/java/lang/StringConcat.java	Tue Jun 16 03:16:41 2020 +0000
@@ -28,11 +28,8 @@
 import org.openjdk.jmh.annotations.OutputTimeUnit;
 import org.openjdk.jmh.annotations.Param;
 import org.openjdk.jmh.annotations.Scope;
-import org.openjdk.jmh.annotations.Setup;
 import org.openjdk.jmh.annotations.State;
-import org.openjdk.jmh.infra.Blackhole;
 
-import java.util.Random;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -54,6 +51,8 @@
 
     public byte byteValue = (byte)-128;
 
+    public String emptyString = "";
+
     @Benchmark
     public String concatConstInt() {
         return "string" + intValue;
@@ -65,6 +64,16 @@
     }
 
     @Benchmark
+    public String concatEmptyRight() {
+        return stringValue + emptyString;
+    }
+
+    @Benchmark
+    public String concatEmptyLeft() {
+        return emptyString + stringValue;
+    }
+
+    @Benchmark
     public String concatMethodConstString() {
         return "string".concat(stringValue);
     }