Problem with StringBuffer

Patrick Tullmann tullmann at cs.utah.edu
Wed Mar 29 09:27:09 PST 2000


> I think the actual problem is not in the StringBuffer size, but in the
> copy done when the buffer is un-shared; after all, unless the StringBuffer
> jump down from 1Mb to 1 byte, a single instance would not be a big problem;
> but having many tokens with a lot of wasted memory would be ...

I whipped up a quick patch for this... I tested it so I know that it
doesn't break anything new.  However, I don't know if it will fix your 
problem.  :)

Basically, in the String(StringBuffer) constructor, I copy the
stringbuffer's contents if used + SLOP < buffer.length.

For systems that create a string buffer, stringize it, and then throw
away the string buffer, this may introduce an extra copy while only
saving a small amount of memory.

-Pat

----- ----- ---- ---  ---  --   -    -      -         -               -
Pat Tullmann                                       tullmann at cs.utah.edu
       Don't hate yourself in the morning -- sleep until noon!


Index: String.java
===================================================================
RCS file: /cvs/kaffe/kaffe/libraries/javalib/java/lang/String.java,v
retrieving revision 1.27
diff -u -u -r1.27 String.java
--- String.java	1999/10/12 02:29:47	1.27
+++ String.java	1999/12/18 23:46:43
@@ -20,6 +20,12 @@
 
 final public class String implements Serializable, Comparable {
 
+	/**
+	 * Maximum slop (extra unused chars in the char[]) that
+	 * will be accepted in a StringBuffer -> String conversion.
+	 */
+	private static final int STRINGBUFFER_SLOP = 32;
+
 	// Note: value, offset, and count are not private, because
 	// StringBuffer uses them for faster access
 	char[] value;
@@ -52,11 +58,23 @@
 
 public String (StringBuffer sb) {
 
-	// mark this StringBuffer so that it knows we are using it
+	// mark the StringBuffer so that it knows we are using it
 	sb.isStringized = true; 
+
+	if ((sb.used + STRINGBUFFER_SLOP) > sb.buffer.length) {
+		value = new char[sb.used];
+		System.arraycopy(sb.buffer, 0,
+				 value, 0, sb.used);
+		count = sb.used;
 
-	count = sb.used;
-	value = sb.buffer;
+		// StringBuffer is free to reuse its buffer again
+		sb.isStringized = false; 
+	}
+	else {
+		// Just point directly to the StringBuffer's char[]
+		count = sb.used;
+		value = sb.buffer;
+	}
 }
 
 public String( byte[] bytes) {


More information about the kaffe mailing list