Quite often you would need to append two strings or maybe more together. There are multiple ways to do this in C# – we’re going to look at appending strings by just concatenating them, or by making use of the C# StringBuilder
class.
String Concatenation
In the .NET Framework this method of appending strings can be very costly on system resources. This is because the string
class is immutable, which means that the string itself is never changed when another string is concatenated to it. The .NET Framework will write the new concatenated string to a different memory location while the old string is also in memory. Then when finished creating the new string, the old string will be deleted. This process can be very time consuming when concatenating very large strings.
The StringBuilder Class
Using this class is the recommended way of concatenating strings with the .NET Framework. The System.Text.StringBuilder
class has an Append()
method which can be used to add text to the end of the existing text in the StringBuilder
.
Speed Tests
Below is an example which proves that the StringBuilder
is a much faster way of appending strings together.
First we are going to append strings using the normal string concatenation method. As you can see below I created a loop and I am performing 100,000 string concatenations. I am also recording the start and end times of this process so that we can compare them with the StringBuilder
‘s times.
Console.WriteLine("Concatenate strings..."); Console.WriteLine(string.Format("Start: {0}", DateTime.Now.ToLongTimeString())); string s1 = string.Empty; for (int i = 0; i < 100000; i++) { s1 += i.ToString(); } Console.WriteLine(string.Format("End: {0}", DateTime.Now.ToLongTimeString()));
Next we are going to do a similar loop but this time we are going to use the StringBuilder
class.
Console.WriteLine("Use StringBuilder..."); StringBuilder sb = new StringBuilder(); Console.WriteLine(string.Format("Start: {0}", DateTime.Now.ToLongTimeString())); for (int i = 0; i < 100000; i++) { sb.Append(i.ToString()); } Console.WriteLine(string.Format("End: {0}", DateTime.Now.ToLongTimeString()));
When we run this application we get the following screen:
As can be seen in the above screenshot, the StringBuilder
is clearly much faster than the normal string concatenation method. It is always advisable to use the StringBuilder
class when appending strings together, especially if you are appending more than two or three strings together.
I hope you found this article useful. Stay tuned to this blog for more articles in the near future.
Dave