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

Ben Maurer bmaurer at users.sourceforge.net
Wed Aug 20 01:07:04 EDT 2003


While playing around with string allocation, I found something funky.
Using this code:

        using System;
        using System.Text;
        
        class T {
        	static void Main ()
        	{
        		StringBuilder b = new StringBuilder ();
        		for (int i = 0; i < 5000; i++)
        			b.AppendFormat ("{0} {1}", "Hello", "World");
        	}
        }

and running it with --profile, I got the following:

     234 KB System.Text.StringBuilder::.ctor(string,int,int,int)
         234 KB     5001 System.Char[]                                   
  Callers (with count) that contribute at least for 1%:
        5001  100 % System.Text.StringBuilder::.ctor()

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 did a quick test and it seems that the .AppendFormat function is not
called by mcs when compiling corlib, however I think that we should
still try to fix this issue.

I suggest that we move the format parsing logic to StringBuilder.

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.

-- Ben




More information about the Mono-devel-list mailing list