The problems with StringBuilders...

David Daney ddaney@avtrex.com
Tue Oct 4 16:14:00 GMT 2005


Andrew Haley wrote:
> David Daney writes:
>  > We had an enlightening (for me anyhow) discussion on IRC about the 
>  > problems with Sun's new StringBuilder class.
>  > 
>  > Summary:
>  > 
>  > StringBuilder is kind of useless.  Because it is unsynchronized, the 
>  > results of StringBuilder.toString() cannot share the underlying char 
>  > array (a copy of the array must be made).  This is because there are 
>  > race conditions that would result in a String changing its value after 
>  > it is created if a copy were not made.
> 
> I see how this could happen, yes.
> 
>  > Having to copy the contents probably has a much overhead as all the
>  > synchronization required by the StringBuffer that it replaces (and
>  > that can share the array).
> 
> I doubt it.  I'd like to see some profile measurements to prove it.
> Besides, is there any reason not simply to synchronize
> StringBuilder.toString() ?
> 
>  > TODO:
>  > 
>  > If the compiler could do some sort of escape analysis on the 
>  > StringBuilder objects,
> 
> If the compiler could do escape analysis we'd have much better
> performance, for sure.  However, inheritance makes this very hard to
> do in most cases.  It's on my list.
> 

For the trick I am thinking of, only a very simple type of escape 
analysis is required.  The only thing you would have to know is if a 
reference (to StringBu[ild|ff]er) escapes.  I think something similar is 
done in the aliasing analysis that the back end does, but I am not 
familiar enough with the code to know for sure.

On a related note:  If someone were to point me to likely places in the 
back end where something like this could be done, I might try hacking 
around a bit.

David Daney



More information about the Java mailing list