C# and the StringBuilder class
This morning I was working on a project at work. It's a Web Application using the ASP .NET 2.0 framework and C# as a code behind language. My friend Ioannis came over to see what was I doing and when he saw I was appending some strings together he asked me this question: "are you using a StringBuilder to use those strings?". And I replied with this answer: "no, I am not". This kind of stupid dialog came over because last week we were discussing about using StringBuilders instead of the default String class operators to append strings each other in Java. It seemed using the StringBuilder class resulted in an overall performance gain. It was then when I asked: "don't tell me this happens with C#, too?". And he answered: "yes, it does!".
So, what's the matter with StringBuilders in C#?
It seems the same thing happens with Strings, C# and Java. Here is a copy paste from the MSDN web page about the StringBuilder usage:
The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
So I decided to run some tests to see how much it was worth to change my code to use the StringBuilder class, because I use the string '+' operator a lot in my program, and the results are simply amazing. Here you can find a chart comparing the times it took to concatenate a given number of strings using both methods. See for yourself and then... use StringBuilders from now on!
Here's the source code i used if you want to try it for yourself:
You can download the external timer classes from The Code Project.