2/9/09

StringBuilder.AppendFormat vs String.Format

I am a bit ashamed of not knowing this until now…

String.Format()

Actaully creates an instance of StringBuilder and delegates all its formatting work to AppendFormat() method to the StringBuilder

So, the following is bad coding:

// creates a string that looks like “item=abc,item=xyz,”
StringBuilder sb = new StringBuilder();
foreach(object obj in myCollection)
{
sb.Append(string.Foramt(“item={0},”, obj));
}

If this loops 1000 times, 1000 StringBuilder instances will be created (calls ctor, allocates memory from managed heap, etc) in the loop

Instead, something like below would be more efficient

StringBuilder sb = new StringBuilder();
foreach(object obj in myCollection)
{
sb.ApppendFormat(“item={0},”, obj);
}

This uses only one instance of StringBuilder

From now on, you will see me using StringBuilder.AppendFormat more, except simpler cases (because one line of String.Format is still more readable!)

0 comments:

Labels