Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8247605

Avoid array allocation when concatenating with empty string

    XMLWordPrintable

Details

    • b02

    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.

      Attachments

        Issue Links

          Activity

            People

              tvaleev Tagir Valeev
              tvaleev Tagir Valeev
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: