OptimizeStringConcat does not preallocate StringBuilder

Aleksey Shipilev aleksey.shipilev at oracle.com
Fri Jan 22 13:29:56 UTC 2016

On 01/22/2016 03:59 PM, Radim Vansa wrote:
> I was wondering whether in these simple cases (without a loop) there 
> is any reason why the strings1-3 could not be retrieved before 
> constructing the StringBuilder with proper sum of lengths of used 
> strings.

Actually, OptimizeStringConcat is supposed to do effectively that for
all-String concat, like string1 + "-" + string2 + "-" string3: pull the
argument lengths, figure out the final storage size, allocate it, copy
strings into it, and then invoke a copy-less String constructor,
materializing the String. This bypasses StringBuilder, so there is no
need for "preallocating" it.

> I've observed this through JFR as TLAB allocations, so I assume
> that? this is really happening - for some reason the allocations are
> not eliminated.

Note that you still have to allocate the backing storage for a final
String, which will manifest in (TLAB) allocations. I am not sure if
those allocations would be attributed to StringBuilder after
OptimizeStringConcat transformed the code. Also note that
OptimizeStringConcat is a C2 optimization, so if you happen to run the
code in C1, you will see the good ol' StringBuilder.

> Is this just not-implemented-yet, or are there any reasons against this?

OptimizeStringConcat implementation is quite complicated and fragile. It
might very well be that you've stepped on some issue in there. If you
really did, contact hotspot-compiler-dev with your test case!

N.B.: A carte-blanche way to deal with OptimizeStringConcat is to allow
runtime to select the appropriate code for String concatenation, rather
than pushing C2 to decipher and rewrite what javac had lowered the
concatenation into. JEP 280 "Indify String Concatenation" covers this,
and many other tricky corner cases:


More information about the hotspot-runtime-dev mailing list