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

Ben Maurer bmaurer at users.sourceforge.net
Wed Aug 20 11:34:12 EDT 2003


On Wed, 2003-08-20 at 09:10, Paolo Molaro wrote:
> 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
> becomes:
> 
> 	StringBuilder s = new StringBuilder ();
> 	FormatHelper (s, ...);
> 	return s.ToString ();
Ok, Implementing this right now, a patch is coming in a bit.
> 
> > 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).
Maybe we should have some TextWriters store their own StringBuilder and
pass it to the FormatHelper method, that way we save on the char []
allocation. In fact, inside of TextWriter we could have:

	StringBuilder cachedFormatter;

And init it on the first call to a Format function.

-- Ben




More information about the Mono-devel-list mailing list