StringBuffer.build() - a way to create strings without unnecessary allocations
tom.hawtin at oracle.com
Thu Dec 9 01:54:51 UTC 2010
On 08/12/2010 23:03, Jaroslav Tulach wrote:
> I've been investigating the memory allocations during NetBeans start. I've
> noticed that we are allocating about 60MB of char mostly due to parsing of
> various configuration files. Suprisingly at least half of these 60MB is
> garbage collected quickly. This is because we use StringBuffer/Builder to
You should find that short-lived memory allocations are very well
handled. If half the memory allocations are going to be long-lived, then
the short-lived allocations should be relatively insignificant.
> That is why I decided to create my patch. It adds StringBuffer.build() method
> which can create Strings without unnecessary copying. It adds
This is how StringBuffer was implemented before 1.5. It turns out that
this is not technically thread-safe for StringBuffer, and StringBuilder
would obviously allow mutable Strings.
Also there is the problem that the StringBuffer char will typically be
longer than necessary, so pruning is generally a good idea.
You might find that you can reduce memory churn by retaining the same
StringBuffer object, removing the contents between uses. But this is
likely to make a mess of your code, and is unlikely to give much actual
More information about the core-libs-dev