Gap Buffer based AbstractStringBuilder implementation

Andrew John Hughes gnu_andrew at
Sun Nov 22 00:33:55 UTC 2009

2009/11/20 Osvaldo Doederlein <opinali at>:
> Hi Goktug,
> Looks like good stuff. And it remembers me from another old issue: patterns
> of code that demand data copying that could often be avoided. Every
> StringBuffer/StringBuilder is ultimately consumed by a toString() invocation
> to produce the result String, and in 99% of all uses, only one such String
> is produced and the buffer object is immediately discarded. So, toString()
> could pass the internal char[] to the String constructor, instead of forcing
> its copy. The API is coded conservatively to always do that copy, because in
> 1% of cases people reuse the buffer, and also to trim the char[]; for
> long-lived strings it would suck to retain extra chars in the heap. But
> these cases are the exception rather than the rule, and we can just invent a
> new method, e.g. toStringShared(), so the developer would only call that
> when the tradeoff is positive: when the product String is short-lived and
> the builder is not reused.

FWIW, we had something along these lines in GNU Classpath.  We
couldn't add a method without breaking the Java specification for
java.lang.StringBuffer/Builder, so instead we created an internal
duplicate (CPStringBuilder) which is now used by internal code in
place of StringBuilder/Buffer.  While we took the 'never copy'
approach to begin with, we ended up with a system where toString set a
flag rather than copying, so that methods in the class that modify the
buffer could check this and perform the copy.  This moved the copy
from the toString method which everyone has to call to post-toString()
modification calls which occur in the 1% of cases you mention.  Such
post-toString modifications copy the buffer and reset the flag.
Andrew :-)

Free Java Software Engineer
Red Hat, Inc. (

Support Free Java!
Contribute to GNU Classpath and the OpenJDK

PGP Key: 94EFD9D8 (
Fingerprint: F8EF F1EA 401E 2E60 15FA  7927 142C 2591 94EF D9D8

More information about the core-libs-dev mailing list