JDK-6650182 : new String(string1 + string2) optimization
  • Type: Enhancement
  • Component: hotspot
  • Sub-Component: compiler
  • Affected Version: 7
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: solaris_9
  • CPU: sparc
  • Submitted: 2008-01-14
  • Updated: 2010-05-10
  • Resolved: 2010-01-08
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 7
7Resolved
Related Reports
Duplicate :  
Relates :  
Description
The optimization is to identify patterns such as:

    String s = new String(string1 + string2);

In this example 'string1' and 'string2' are type String. A javac compilation of the above code and subsequent de-compile of the code above to be translated into:

     String s = new StringBuilder().append(string1).append(string2).toString();

In the above code, a new char[] will be allocated with the 'new StringBuilder()' of a default size 16 chars. If string1 happens to exceed 16 chars in length, a new char[] will be allocated. And, subsequently, a new char[] will yet again be allocated when string2 is appended, (unless, of course, string2 is null). In addition, yet another char[] will be allocated by the toString() method, (See the StringBuilder optimization 1 pager for the elimination of that char[] allocation). Hence, there exists a very good probability that 4 char[] allocations could occur in the above code. The first one at StringBuilder() constructor time, a second in append(string1), a third in append(string2) and a fourth in toString().

Hence, the optimization idea here is to identify the above pattern and use the length of String string1 and string2 to allocate the StringBuilder. In other words, the optimization would essentially produce the following code (in Java):

String s = new StringBuilder(string1.length() + string2.length()).append(string1).append(string2).toString();

The above code, when also used with the optimization identified in the StringBuilder.toString() optimization (6650179) would allocate only 1 char[].