OptimizeStringConcat does not preallocate StringBuilder

Radim Vansa rvansa at redhat.com
Fri Jan 22 12:59:09 UTC 2016


Hi,

I have been analyzing memory allocations in an app and I've noticed that 
non-trivial amount of allocations come from StringBuilder growing its 
buffer. These came from simple toString() implementations that looked 
like string1 + "-" + string2 + "-" string3. In this case, the bytecode 
contains arg-less StringBuilder ctor which allocates 16-char array, 
which was insufficient here. On the appends, this buffer had to be 
expanded, causing allocations and copying. In the end, common 
StringBuilder.toString() was used, therefore triggering another 
allocation and copy to the immutable String.

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.

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.
Even better, in the end the code could call (currently non-existent) 
invalidateToString() that would check that the contents length equals 
the buffer length, and in this case call the copy-less String(value, 
true) constructor, resetting the SB's buffer in the end (so this would 
not endanger the immutability of String).

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

Thanks

Radim

-- 
Radim Vansa <rvansa at redhat.com>
JBoss Performance Team



More information about the hotspot-runtime-dev mailing list