Recently I was asked the question if I knew the difference between a String and StringBuilder. The expected answer, which was not my answer, was String is immutable while StringBuilder is mutable. My ill-informed response was, “String is not immutable. I constantly change the values of Strings in my code.” The response I got was, “While String values can be changed, you’re actually creating a new String object in memory every time you do so. You should’t concatenate a string inside a loop. For that scenario, StringBuilder would give you better performance.” Sill thinking I was right, I decided to do a performance test myself with the following code:
void Test1()
{
string str = "s";
for (int index = 0; index <= 100; index++)
{
str += index.ToString();
}
Console.WriteLine(str);
}
void Test2()
{
StringBuilder str = new StringBuilder("s", 200);
for (int index = 0; index <= 100; index++)
{
str.Append(index.ToString());
}
Console.WriteLine(str.ToString());
}
Test1 concatenates a string in for loop while Test2 concatenates a StringBuilder in a for loop.
I used Visual Studio’s performance analysis (Debug >> Start Performance Analysis) to monitor CPU usage and managed memory allocation.
As you can see, CPU usage was relatively high between 0-1 seconds and there was a high amount of memory allocation for System.String.
In Test2, CPU usage was lower between 0-1 seconds and there was significantly less memory usage throughout the test. If you’re wondering why I’m only looking at the 0-1 second range in the CPU usage report, it’s because each test took less then a second to run.
What I learned was that I was completely wrong with my response. StringBuilder does offer better performance when concatenating within a loop. I can now honestly say I’ve been schooled in the art of .NET performance and memory usage. Being a .NET developer for the past 6 years, I felt like a phony. Scott Hanselman knows what I’m talking about. I guess when it comes to being a developer there is always room for growth.
Always pass on what you have learned.
br> br>