StringBuilder vs String Concatenation in C#

Beril Kavaklı
2 min readApr 12, 2020

--

While coding, we sometimes need to concatenate two or more string and generally make it with ‘+’ operator in C#. Yeah that works but may return from code review. You may see a reviewer comment such that “You should use StringBuilder instead of string concatenation!” Okay but why? Why should I use StringBuilder instead of just using ‘+’?

Let’s see the differences between these two…

  1. Memory Allocation

There are two types of data structures to keep variable in memory: Stack and Heap. In C# String is kept in heap, it occupies memory with initial value. If we change the value, it hasn’t changed indeed. Instead, another memory allocation is made and the first allocation is cleaned by garbage collector. For StringBuilder, the allocated memory is extendable. If we concatenate a lot of string, using StringBuilder is more effective.(https://www.geeksforgeeks.org/stringbuilder-in-c-sharp/)

2. Performance

As you may notice, due to the new memory allocation, StringBuilder is better in terms of performance. If you want to show district results, you can try on your computer with the code below. (https://support.microsoft.com/en-us/help/306822/how-to-improve-string-concatenation-performance-in-visual-c)

const int sLen=30, Loops=5000;
DateTime sTime, eTime;
int i;
string sSource = new String('X', sLen);
string sDest = "";
//
// Time string concatenation.
//
sTime = DateTime.Now;
for(i=0;i<Loops;i++) sDest += sSource;
eTime = DateTime.Now;
Console.WriteLine("Concatenation took " + (eTime - sTime).TotalSeconds + " seconds.");
//
// Time StringBuilder.
//
sTime = DateTime.Now;
System.Text.StringBuilder sb = new System.Text.StringBuilder((int)(sLen * Loops * 1.1));
for(i=0;i<Loops;i++) sb.Append(sSource);
sDest = sb.ToString();
eTime = DateTime.Now;
Console.WriteLine("String Builder took " + (eTime - sTime).TotalSeconds + " seconds.");
//
// Make the console window stay open
// so that you can see the results when running from the IDE.
//
Console.WriteLine();
Console.Write("Press Enter to finish ... ");
Console.Read();

3. Readable Code

Coding style is subjective and it heavily depends on the programmer. On the other hand, producing readable code is especially important for large teams. I think StringBuilder is cleaner and more understandable than concatenation. Choice is yours :)

--

--