The problems with StringBuilders...
David Daney
ddaney@avtrex.com
Mon Oct 3 23:09:00 GMT 2005
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. 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).
TODO:
If the compiler could do some sort of escape analysis on the
StringBuilder objects, in cases where a instance of StringBuilder could
not escape into another thread, it could rewrite
StringBuilder.toString() into a call to a nearly equivalent method that
does share the backing array. This could only be done when the
capabilities of the runtime library were known (i.e. the runtime had the
non-copying toString equivalent). The optimization could not be done
when generating class files.
Once you had this optimization in place you could convert all
StringBuffers that don't escape into StringBuilder as well. This way
you could get all the advantages of StringBuilder without having to
actually re-write any of your code.
Someone should get started on this right away. :)
David Daney
More information about the Java
mailing list