classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

StringBuffer.substring sharing


From: Bryce McKinlay
Subject: StringBuffer.substring sharing
Date: Wed, 24 Sep 2003 18:19:57 +1200

After I checked in Ralph Loader's fix for StringBuffer.substring the other day, Ralph pointed out that my modification had changed the meaning of the patch slightly:

On Monday, Sep 22, 2003, at 20:45 Pacific/Auckland, Ralph Loader wrote:

My interpretation of the original code was that it was meant to prevent
the possibility that a small substring of a large StringBuffer would
prevent the large array being gc'd.

The patch you checked in breaks this.  Consider:

String Foo()
{
  StringBuffer b = new StringBuffer();
  ... put a megabyte of stuff into b ...
  String ignored = b.toString(); // sets b.shared
  return b.substring (0, 1);
}

The 1 character String returned from Foo now has it's contents stored in
a megabyte char[], and that array has no other references.

Passing ((len << 2) >= value.length) rather than StringBuffer.shared to
the String constructor prevented this.

Its hard to say what is optimal here, as you can also argue that if the string is already shared then its reasonable to share even if the substring is small. However, having to copy a small string unnecessarily doesn't seem as bad as potentially wasting a lot of memory in the scenario above. So, I'm checking in the following patch, which reverts to the behaviour of Ralph's original patch.

Attachment: StringBuffer2.patch.txt
Description: Text document



Regards

Bryce.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]