[Mono-devel-list] String Allocation in StringBuilder.AppendFormat

Paolo Molaro lupus at ximian.com
Wed Aug 20 09:10:12 EDT 2003

On 08/20/03 Ben Maurer wrote:
> Looking at the StringBuilder.AppendFormat code, it just does:
> 	Append (String.Format (...));
> Inside the Format code, a new StringBuilder is allocated to handle the
> formatting.
> I suggest that we move the format parsing logic to StringBuilder.

I don't see any reason to move the code around. Just change the current
String.Format to an internal method String.FormatHelper that takes
an additional argument, a StringBuilder. This way it can be used
directly by the StringBuilder.AppendFormat functions and String.Format

	StringBuilder s = new StringBuilder ();
	FormatHelper (s, ...);
	return s.ToString ();

> One other, related, idea is to eliminate the allocation of the
> StringBuilder in TextWriter.Write (string, object []). Instead of
> calling String.Format (and thus allocating a StringBuilder), we could
> make a private overload that would take in a TextWriter. We could then
> make a formatter that used TextWriter.Writer, rather than
> StringBuilder.Append to write out the values.

I don't think that will be a win in practice: you're just saving two
allocations that in the context of the Format code are probably
just a small part and you're going to have code duplication and pay for
more TextWriter calls that may be potentially expensive (synchronized,
writes to disk etc).


lupus at debian.org                                     debian/rules
lupus at ximian.com                             Monkeys do it better

More information about the Mono-devel-list mailing list