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

Ben Maurer bmaurer at ximian.com
Sat Jan 15 23:19:25 EST 2005

Hey guys,

Attached is a patch that speeds up StringBuilder in some common cases.
The goal of this patch is to avoid allocations of the string builder
buffer when possible. I do this in two ways:

1. Lazily allocate the buffer

When you create a new string builder, it will have an empty string, "",
as the buffer. This avoids the first allocation

2. Make the first append not allocate a buffer

Rather than allocate a buffer by the time of the first append, this just
sets the cached string and the buffer equal to the string we get in.

Doing this prevents allocations in a few common cases:

Case 1:

	StringBuilder sb = new StringBuilder ();

Here, we saved allocating the buffer at all.

Case 2:

	StringBuilder sb = new StringBuilder ();
	sb.Append ("foo");
	sb.ToString ();

Here, we avoided two allocations: the buffer in the string builder, and
the string that would have been created from ToString. We just return
the same string as was passed into append.

Case 3:

	StringBuilder sb = new StringBuilder ();
	sb.Append ("0123456789");
	sb.Append ("0123456789");
	sb.ToString ();

We saved one allocation here. The default size of a StringBuilder is 16.
However, in the second append, it knows that this will not be large
enough. So it is able to make its first buffer 32 chars.

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.

-- Ben

More information about the Mono-devel-list mailing list