C# String.Format() and StringBuilder

Note: If you are not familiar with String.Format and StringBuilder you can learn about it in my blog post C# String.

Recently, I saw some code that looked something like this:

1 StringBuilder builder = new StringBuilder();
2 builder.Append(String.Format("{0} {1}", firstName, lastName));
3 // Do more with builder...

Now, I don’t wana get into arguments about how String.Concat() is more performant here. String.Format() allows code to be more easily localized and it is being used for that purpose here. The real problem is that StringBuilder.AppendFormat() should be used instead:

1 StringBuilder builder = new StringBuilder();
2 builder.AppendFormat("{0} {1}", firstName, lastName);
3 // Do more with builder...

The reason that this is important is because, internally, String.Format() actually creates a StringBuilder and calls StringBuilder.AppendFormat()! String.Format() is implemented something like this:

1 public static string Format(IFormatProvider provider, string format, params object[] args)
2 {
3   if (format == null || args == null)
4    throw new ArgumentNullException((format == null ? "format" : "args"));
5 
6   StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
7   builder.AppendFormat(provider, format, args);
8   return builder.ToString();
9 }

you can see the actual implementation in the source code for the runtime of .NET Core. Here is the link for the same: String.Manipulation.cs

In String.Manipulation.cs file you will find the Format method:

From the above code, you can see that Format method calls an internal method FormatHelper.

Now, the FormatHelper method uses StringBuilder for formatting the text using StringBuilderCache.

It turns out that the formatting logic is actually implemented in StringBuilder.AppendFormat(). So, the original code actually caused a second StringBuilder to be utilized when it wasn’t needed.

This is also important to know if you are trying to avoid creating a StringBuilder by concatentating strings with String.Format(). For example:

1 string nameString = "<td>" + String.Format("{0} {1}", firstName, lastName) + "</td>"
2   + "<td>" + String.Format("{0}, {1}", id, department) + "</td>";

That code will actually create two StringBuilders, if the size of formatted string is greater than MaxBuilderSize, used in StringBuilderCache, which is set to 360. So, creating one StringBuilder and using AppendFormat() will be more performent:

1 StringBuilder nameBuilder = new StringBuilder();
2 nameBuilder.Append("<td>");
3 nameBuilder.AppendFormat("{0} {1}", firstName, lastName);
4 nameBuilder.Append("</td>");
5 nameBuilder.Append("<td>");
6 nameBuilder.AppendFormat("{0}, {1}", id, department);
7 nameBuilder.Append("</td>");
8 string nameString = nameBuilder.ToString();

I decided to run some performance tests to verify my claims. First, I timed code that demonstrates the very reason that StringBuilder exists:

 1 const int LOOP_SIZE = 10000;
 2 const string firstName = "Shadman";
 3 const string lastName = "Kudchikar";
 4 const int id = 1;
 5 const string department = ".NET Team";
 6 
 7 static void PerformanceTest1()
 8 {
 9   string nameString = String.Empty;
10 
11   for (int i = 0; i < LOOP_SIZE; i++)
12     nameString += String.Format("{0} {1}", firstName, lastName);
13 }

The above code creates a new string and then concatenates to it inside of a for-loop. This causes two new strings to be created on each pass–one from String.Format() and one from the concatenation. This is woefully inefficient.

Next, I tested the same code modified to use a StringBuilder with String.Format():

1 static void PerformanceTest2()
2 {
3   StringBuilder builder = new StringBuilder((firstName.Length + lastName.Length + 1) * LOOP_SIZE);
4 
5   for (int i = 0; i < LOOP_SIZE; i++)
6     builder.Append(String.Format("{0} {1}", firstName, lastName));
7 
8   string nameString = builder.ToString();
9 }

Finally, I tested code that uses StringBuilder.AppendFormat() instead of String.Format():

1 static void PerformanceTest3()
2 {
3   StringBuilder builder = new StringBuilder((firstName.Length + lastName.Length + 1) * LOOP_SIZE);
4 
5   for (int i = 0; i < LOOP_SIZE; i++)
6     builder.AppendFormat("{0} {1}", firstName, lastName);
7 
8   string nameString = builder.ToString();
9 }

These three methods ran with the following timings:

For .NET Framework:

1 PerformanceTest1: 0.21045 seconds
2 PerformanceTest2: 0.001585 seconds
3 PerformanceTest3: 0.0010846 seconds

For .NET Core:

1 PerformanceTest1: 0.173821 seconds
2 PerformanceTest2: 0.0012753 seconds
3 PerformanceTest3: 0.0007812 seconds

Obviously, concatenating a string in a loop without using a StringBuilder is amazingly inefficient. And, removing the call to String.Format also yields a performance boost.

Next, I tested the following two methods:

 1 static void PerformanceTest4()
 2 {
 3   string htmlString;
 4   for (int i = 0; i < LOOP_SIZE; i++)
 5     htmlString = "<td>" + String.Format("{0} {1}", firstName, lastName) + "</td><td>"
 6       + String.Format("{0}, {1}", id, department) + "</td>";
 7 }
 8 static void PerformanceTest5()
 9 {
10   StringBuilder builder = new StringBuilder(256);
11 
12   string htmlString;
13   for (int i = 0; i < LOOP_SIZE; i++)
14   {
15     builder.Append("<td>");
16     builder.AppendFormat("{0} {1}", firstName, lastName);
17     builder.Append("</td><td>");
18     builder.AppendFormat("{0}, {1}", id, department);
19     builder.Append("</td>");
20     htmlString = builder.ToString();
21     builder.Length = 0;
22   }
23 }

These two methods ran with the following timings:

For .NET Framework:

1 PerformanceTest4: 0.0050095 seconds
2 PerformanceTest5: 0.0044467 seconds

For .NET Core:

1 PerformanceTest4: 0.0036363999999999997 seconds
2 PerformanceTest5: 0.0019971 seconds

As you can see, it is important to know when to use String.Format and when to use StringBuilder.AppendFormat(). While the performance boosts that can be achieved are fairly small, they are too easy to code.

You can download the performance tests here: https://github.com/kudchikarsk/string-format-performance-test.

Further Reading

C# String.Format() and StringBuilder
Share this

Subscribe to Code with Shadman