[Mono-devel-list] [PATCH] StringBuilder Speedup

Ben Maurer bmaurer at ximian.com
Sun Jan 16 16:00:41 EST 2005


On Sun, 2005-01-16 at 11:09 -0500, Miguel de Icaza wrote:
> Hello,
> 
> > Doing this patch will make the behavior as compared to MSFT a bit
> > different for some pendantic test cases (mostly in terms of the capacity
> > property). However, I think this is a reasonable difference between two
> > impls of the framework.
> > 
> > If nobody objects, I will check this in.
> 
> I do object, there is no reason to change the public interface to the
> class for an optimization.

Well, the docs for Capacity say:

`The StringBuilder dynamically allocates more space when required and
increases Capacity accordingly. For performance reasons, a StringBuilder
might allocate more memory than needed. The amount of memory allocated
is implementation-specific.'

The other difference is this test case:

StringBuilder sb = new StringBuilder ();
sb.Append ("Blah");
string s = sb.ToString ();

Console.WriteLine (object.ReferenceEquals ("Blah", s));

My impl saves allocations and returns the string that was passed in by
Append. This is another detail that is really impl specific. However,
this difference does not cause any problems in correctly written
programs. We already have similar differences (where we return the same
pointer in cases where MSFT doesnt).

> I have another question: what is the behavior in this case:
> 
> 	new StringBuilder ("")

No buffer is allocated. If you call .ToString (), the return value will
be equal, pointerwise to "".

> It is also a common pattern;  Notice that we should also take care of
> these cases (from the public interface perspective):
> 
> 	new StringBuilder ()
> 
> and than:
> 
> 	new StringBuilder ("Init string")

Both test cases will work exactly the same except:
      * The second string builder would return a Capacity of "Init
        string".Length
      * If ToString is called on the first, it will be equal,
        pointerwise, to "". ON the second, it will be equal pointerwise
        to "Init string".

No correctly written program will function differently with this patch.

-- Ben




More information about the Mono-devel-list mailing list