Re: StringBuffer/StringBuilder efficiency
On Sun, 27 Sep 2009, Patricia Shanahan wrote:
Roedy Green wrote:
...
Another StringBuilder optimisation that would be useful would be if
the estimate of StringBuilder size were accurate to say with 10 bytes,
then the buffer could be converted to a String without copying it.
...
This would take some care, given the mutable nature of StringBuilder,
but would be possible, given the fact that String and StringBuilder are
in the same package.
One possible design:
1. Add to String a package-only constructor that sets the char[],
length, and offset fields directly.
2. Modify StringBuilder:
Add a boolean field sharedArray, initially false.
In toString, if size is accurate enough, use the new String constructor
and set sharedArray=true.
In state changing method calls that use the old value, such as append,
with sharedArray true, replace the reference to the shared char[] with a
reference to a copy of it and set sharedArray=false.
Actually, in the specific case of append, you can carry on using the
shared array - if the String only cares about characters 1-10 of the
buffer, then appending more stuff in positions 11-20 is fine.
It's delete, insert, replace, reverse, and setCharAt that you need to
worry about. And perhaps setLength.
Perhaps instead of having a boolean sharedArray, you could have an int
sharedCharLimit, being an index into the array beyond which there are no
shared characters, initially zero. Modifications to the buffer after
sharedCharLimit wouldn't trigger copying of the buffer.
Of course, this is mainly precautionary. Often, a toString() call is the
last event in the life of a StringBuilder before unreachability.
Almost always, i suspect. Certainly a common case that looks worth
optimising for.
tom
--
There is no latest trend.