JDK-8247605 : Avoid array allocation when concatenating with empty string
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2020-06-15
  • Updated: 2024-11-20
  • Resolved: 2020-06-16
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 16
16 b02Fixed
Related Reports
Relates :  
Description
Currently, when concatenation of two strings is evaluated and one of them happens to be an empty string, another is copied completely, including the backing array (see java.lang.StringConcatHelper::simpleConcat). While creating a new String instance is required in this case by JLS 15.18.1, it's still allowed to reuse the internal array reducing the allocations and CPU usage.

A simple benchmark demonstrates the possible improvement:

@Param({"", "longlonglongline"})
  String data;

  @Param({"", "longlonglongline"})
  String data2;

  @Benchmark
  public String plus() {
    return data + data2;
  }

Without patch it takes about 15ns to concatenate two empty strings and about 20ns to concatenate an empty string with "longlonglongline". After the patch is applied, the average time goes down to 6.6-7.0 ns.
Comments
The following changeset mistakenly refers to this issue: http://hg.openjdk.java.net/jdk/jdk/rev/66992d8c1441 It should refer to JDK-8244288 instead.
11-08-2020

Changeset: 0a108f9e Author: Tagir F. Valeev <tvaleev@openjdk.org> Date: 2020-06-16 03:16:41 +0000 URL: https://git.openjdk.java.net/lanai/commit/0a108f9e
02-07-2020

Changeset: 0a108f9e Author: Tagir F. Valeev <tvaleev@openjdk.org> Date: 2020-06-16 03:16:41 +0000 URL: https://git.openjdk.java.net/panama-foreign/commit/0a108f9e
02-07-2020

Changeset: 0a108f9e Author: Tagir F. Valeev <tvaleev@openjdk.org> Date: 2020-06-16 03:16:41 +0000 URL: https://git.openjdk.java.net/amber/commit/0a108f9e
02-07-2020

URL: https://hg.openjdk.java.net/jdk/jdk/rev/20d92fe3ac52 User: tvaleev Date: 2020-06-16 03:17:50 +0000
16-06-2020