The Difference between String and StringBuilder in C#

AramT
54.3K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

To benchmark the difference between String and StringBuilder, I prepared a simple program to measure the performance of a huge list of strings when processed through a loop. I’ve used the Visual Studio’s diagnostics tool that displayed the CPU process percentage as well as the memory consumption.

The below code declares a gigantic list of 200K strings containing strings starting from ‘1000’ and upwards.

List hugeList = Enumerable.Range(1000, 200000).Select(n => n.ToString()).ToList(); And here is the code that we loop through this list using the string concatenation operation (+=) :

String concatResult = "";
foreach (String value in hugeList)
{
    concatResult += value;
}

While running the code, you will notice the diagnostics tool for visual studio will start monitoring the memory and CPU activity.

Notice when using the String concatenation operator += , even though we are updating the concatResult variable within the loop, because String object is immutable, it will not replace its value in the memory but it will create a new one keeping the old one intact.

so there is performance overkill when having a long loop on a String object with the += concatenation operator.

Processing this list with the string concatenation operator += took 2 minutes 30 seconds. Which is massive time and very high resource usage due to creating high number of String objects in memory.

alt text

Now let’s boost the performance, and build our gigantic list of strings in the loop using the correct methodology, the StringBuilder class.

The below code defines a StringBuilder object, and then appends the string being looped. And after that using the ToString() method on the stringBuilder’s object instance the result of appending all the strings in the huge list can be retrieved anywhere.

StringBuilder stringBuilder = new StringBuilder();
String stringBuilderResult = "";
foreach (String s in hugeList)
{
    stringBuilder.Append(s);
}
 
stringBuilderResult = stringBuilder.ToString();

Note in the below screenshot, the total processing time for building the 200K string object, is 99ms only.

alt text

Have you just noticed the significantly enormous difference between using String and StringBuilder in such huge lists?

Bottom line: Use only StringBuilder when you want to concatenate (or build) a String when you have a large list or list of dynamic size.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content