Difference between String and StringBuilder in C#.


C# String vs StringBuilder: In this article will explain the difference between String and StringBuilder. We also perform a benchmark on String Vs StringBuilder, to get a clear idea about performance. This helps us to understand when to use String vs SringBuilder, and which one is faster between String and StringBuilder. 

In C#, the String object is a sequential collection of `System.Char` objects which represent strings. Both String and StringBuilder contain text values. But the main difference between String and StringBuilder is String is immutable and StringBuilder is mutable.

Let's understand what are Immutable and Mutable in more detail:

# Immutable Strings: Immutable Strings mean when a variable of string type is created, it cannot be modified, and its value is stored in the heap memory. If we modify the same string variable, then C# complier will create a new instance of string object and allocate new memory on the heap.

And if we manipulate the same string variable multiple times, then it will result in performance degradation. Immutable strings are instances of a `System.String` class. 

# Mutable String: Mutable String means when an operation is performed on the variable containing a string value, it will not create a new instance every time. Also, it will not allocate new space in the memory.

StringBuilder is mutable, hence it is best to use when we need to modify the string variable repeatedly. Mutable strings are instances of a `System.Text.StringBuilder` class. 

# Difference Between String vs StringBuilder.

C# String
C# StringBuilder
1) It represents an immutable string.It represents a mutable string.
2) Immutable strings are unmodifiableMutable strings are modifiable and dynamic in nature.
3) The string class is available in System Namespace.
The StringBuilder class is available in System.Text Namespace
4) It is extremely useful concerning trust since a string would not change as long as we didn't change the reference.
It is extremely useful when we need to perform a lot of text manipulation on the string.
5) It is slow as compared to the StringBuilder object.
It is fast as compared to a String object.

# Code of using String and StringBuilder in C#.

Example 1: Code using String.

string strMsg = "Welcome";
strMsg = strMsg + " to";
strMsg = strMsg + " Codepedia!";            

Here the output would display a msg as "Welcome to Codepedia!". But memory allocation is different as we modify the string 3 times, so it will create 3 different object instances in the memory.

The below diagram illustrates memory allocation using String in C#.

Example 2: Code using StringBuilder.

StringBuilder sbMsg = new StringBuilder();
sbMsg.Append(" to");
sbMsg.Append(" Codepedia!");            

Here we used StringBuilder to display msg and the output would be the same i.e. "Welcome to Codepedia!". In the above code, the StringBuilder variable modifies 3 times, but it will create only one instance in memory.

The below diagram illustrates memory allocation using StringBuilder in C#.


# When to use String vs StringBuilder in C#?

In C#, the String data type is a reference type data object. As a string is immutable, when we combine two or more strings, it creates a new instance and allocates space in memory.

If we have to perform two or three string concatenations or read and compare values then we can use a String.

But if we have to make repeated modifications to a string or concatenate many strings then StringBuilder must be used, as it will increase the performance by not creating a new instance each time, unlike String.

# Benchmark Test String vs StringBuilder.

Here we do a benchmark test over String and StringBuilder by using BenchmarkDotNet nuget package. You can also check our article on Detailed Benchmark on String vs StringBuilder.

Below are two methods that concatenate strings using StringBuilder and String. 

Method 1: Concatenate strings using String.

public  string ConcatUsingString()
	string strData = string.Empty;
	for (int i = 0; i < 1000; i++)
		strData += "Print No : " + i;
	return strData;

Method 2: Concatenate strings using StringBuilder.

public  string ConcatUsingStringBuilder()
	StringBuilder sbData = new StringBuilder();
	for (int i = 0; i < 1000; i++)
		sbData.Append("Print No : " + i);
	return sbData.ToString();

Output: Benchmark String Vs StringBuilder C#
Here the output indicates StringBuilder is faster than String.

Conclusion: Here this article explains the difference between String and StringBuilder. When to use String over StringBuilder. Why and when to use StringBuilder. By using BenchmarkDotNet nuget package we came to know if we need to read or compare strings, or if we have to concatenate two or three strings together, then we must use String. And if we want to perform multiple operations on a string continually, then StringBuilder is always the best choice.

Other Resource:
1) C# String
2) C# StringBuilder

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *