8247605: Avoid array allocation when concatenating with empty string

Reviewed-by: redestad, plevart
This commit is contained in:
Tagir F. Valeev 2020-06-16 03:16:41 +00:00
parent e33ebc7f0a
commit 0a108f9ef2
2 changed files with 20 additions and 3 deletions

View File

@ -406,6 +406,14 @@ final class StringConcatHelper {
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);

View File

@ -28,11 +28,8 @@ import org.openjdk.jmh.annotations.Mode;
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 class StringConcat {
public byte byteValue = (byte)-128;
public String emptyString = "";
@Benchmark
public String concatConstInt() {
return "string" + intValue;
@ -64,6 +63,16 @@ public class StringConcat {
return "string" + stringValue;
}
@Benchmark
public String concatEmptyRight() {
return stringValue + emptyString;
}
@Benchmark
public String concatEmptyLeft() {
return emptyString + stringValue;
}
@Benchmark
public String concatMethodConstString() {
return "string".concat(stringValue);