In C#, the string
and StringBuilder
classes serve different purposes for handling text data.
- The
string
class is immutable, meaning its value cannot be changed once it is created. It is commonly used for string manipulation methods like concatenation, splitting, and replacing. - On the other hand, the
StringBuilder
class is mutable, allowing you to modify its value without creating a new instance in memory each time.
In this article we will learn the Difference between string and StringBuilder in C# with multiple code examples.
In C#, string, and StringBuilder are both used to store and manipulate sequences of characters. However, there are some key differences between these two types that you should consider when choosing which one to use in your code.
- A string is immutable, which means that once you create a string, you cannot modify it. This can make it more efficient when you only need to read or compare strings, but it can be less efficient when you need to build or modify a string repeatedly.
- On the other hand, StringBuilder is mutable, which means that you can change it after it is created. This makes it ideal for situations where you need to build or modify a string repeatedly in a loop, as it can be more efficient than using string for this purpose. However, keep in mind that StringBuilder may use more memory than strings in some cases.
In sort, if you only need to read or compare strings, you should use a string. If you need to build or modify a string repeatedly in a loop, you should use a StringBuilder.
Table of Contents
- 1 Difference between string and StringBuilder in C#
- 2 Benchmark Test between String and StringBuilder in C#
- 3 String in C#
- 4 StringBuilder in C#
- 4.1 StringBuilder memory allocation
- 4.2 Declaration and Initialization of StringBuilder in C#
- 4.3 Setting the capacity and length of the StringBuilder
- 4.4 C# StringBuilder Methods
- 4.5 C# StringBuilder Append and AppendLine Method
- 4.6 StringBuilder AppendFormat Method
- 4.7 C# StringBuilder Insert Method
- 4.8 StringBuilder Remove Method
- 4.9 StringBuilder Replace Method
- 4.10 Use of Indexer in StringBuilderStringBuilder as Indexer
- 4.11 Convert StringBuilder to String
- 5 Summary:
- 6 FAQs
Difference between string and StringBuilder in C#
The differences between the string and StringBuilder are listed below.
C# String | C# StringBuilder |
---|---|
1. The string class is available in System Namespace. | The StringBuilder class is available in System.Text Namespace. |
2. A string instance is immutable (unchangeable). String objects once created cannot be changed. | A StringBuilder class is mutable (changeable), which means if we create a string builder object then we can perform any operation on it. |
3. If we perform any operation on a String instance, it will create a new instance in the heap memory instead of modifying the existing string value. Example: string stringValue = “Hello “; // creating a new string instance instead of modifying the old one. stringValue += “World”; | If we perform any operation on a StringBuilder instance, it will update the existing instance value rather than creating a new one in the memory. Example: StringBuilder sb = new StringBuilder(); sb.Append(“Hello “); sb.Append(“World”); string stringValue = sb.ToString(); |
4. Because String is immutable, it can be used across multiple threads without causing synchronization issues. Thread safety is ensured. | The StringBuilder in C# is not thread-safe since it lacks synchronization. |
5. String is slower as compared to StringBuilder. Its performance degrades when heavy string manipulations or concatenation are involved in a loop. | StringBuilder is mutable, So it provides better performance as compared to the String object because the new changes are made to an existing instance instead of creating the new one in the memory. |
Benchmark Test between String and StringBuilder in C#
Below is a C# benchmark test that compares string concatenation performance versus StringBuilder. We’ll use the popular benchmarking library BenchmarkDotNet
to measure the execution time of these operations.
You must make sure to install BenchmarkDotNet
through NuGet
before running the code.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Text;
namespace ConsoleApp1
{
public class StringVsStringBuilderBenchmark
{
private const int Iterations = 10000;
private readonly string[] stringArray;
private readonly StringBuilder stringBuilder;
public StringVsStringBuilderBenchmark()
{
stringArray = new string[Iterations];
stringBuilder = new StringBuilder();
for (int i = 0; i < Iterations; i++)
{
stringArray[i] = i.ToString();
stringBuilder.Append(i.ToString());
}
}
[Benchmark]
public string ConcatenateStrings()
{
string result = "";
for (int i = 0; i < Iterations; i++)
{
result += stringArray[i];
}
return result;
}
[Benchmark]
public string UseStringBuilder()
{
stringBuilder.Clear();
for (int i = 0; i < Iterations; i++)
{
stringBuilder.Append(stringArray[i]);
}
return stringBuilder.ToString();
}
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<StringVsStringBuilderBenchmark>();
}
}
}
Output:
The above benchmark results show the time taken by each operation. The output provides valuable insights into the performance difference between string concatenation and StringBuilder.
In the above result we can clearly see that the StringBuilder is faster than String.
String in C#
In C#, a string is a sequence of characters represented as a data type. It is immutable, meaning once a string object is created, it cannot be changed. Any operation that appears to modify a string actually creates a new string object in the heap memory.
For example:
string str = "Hello, ";
str += "Shekh";
In the above code, a new string
object is created when "shekh"
is appended to str
.
So, after these two lines of code, the variable str
will hold the value “Hello Shekh”.
It’s important to note that the original string “Hello” remains unchanged in the heap memory, but a new string is created to store the concatenated result.
This is because strings in C# are immutable, meaning they cannot be modified after creation, and any operation that appears to modify a string creates a new string object in the memory.
String memory allocation
Following is the pictorial representation of memory allocation for the string object.
Example of string concatenation
using System;
class Program
{
static void Main(string[] args)
{
string str = "Hello ";
str += "Shekh";
// Here Concatenation (+=) actually creating a new
// string object and releasing the
// reference to the original object.
Console.WriteLine(str);
Console.ReadLine();
}
}
// Output: Hello Shekh
The += operator creates a new string object that contains the combined contents. The previous objects get released for garbage collection.
String concatenation can be done in two ways, either by using the + =
operator or by using the String.Concat
method.
string str = "Hello ";
str = String.Concat(str, "Shekh");
String interning in C#
In C#, sometimes we write a program with multiple instances of the same string.
The CLR (Common Language Runtime) stores single references to all unique strings in a special table known as Intern Pool.
- At compilation time all the unique strings are allocated in the heap memory.
- Only the reference is returned from the “Intern Pool” to the new string variables having the same value.
The following is the pictorial representation of memory allocation for the unique strings.
The following is the Sample example code :
using System;
class Program
{
static void Main(string[] args)
{
string x = "SameString";
string y = "SameString";
string z = "DifferentString";
Console.WriteLine("x == y {0}", Object.ReferenceEquals(x, y));
Console.WriteLine("y == z {0}", Object.ReferenceEquals(y, z));
Console.ReadLine();
}
}
In the above example, the x and y variables have the same reference.
- In C# Strings are immutable.
- Every time we concatenate a string, a new object is created in the heap memory.
- In C# the previous objects which are no longer used are garbage collected.
- Modifying the same string multiple times will hinder the performance.
- In C# use StringBuilder if the string is modifying frequently.
StringBuilder in C#
In C# we use String and StringBuilder to hold text. The only difference is, the String is immutable and StringBuilder is mutable.
The StringBuilder is a dynamic object which belongs to the System.Text namespace. It doesn’t create a new object in the heap memory every time we concatenate a new string.
- In C# the StringBuilder is the better option for concatenating multiple strings together in a loop.
- The string is efficient if we are only concatenating two or three strings.
Method Name | Description |
---|---|
Append | Appends the given information to the end of the current StringBuilder. |
AppendFormat | Replaces a format specifier passed in a string with formatted text. |
Insert | Inserts a string or object into the specified index of the current StringBuilder. |
Remove | It removes/deletes a specified number of characters from the current StringBuilder. |
Replace | Replaces a specified character at a specified index of the current StringBuilder. |
StringBuilder memory allocation
Pictorial representation of memory allocation for the unique strings.
The following is the sample example code of using StringBuilder in C#.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.Append("World");
Console.WriteLine(sb);
Console.ReadLine();
}
}
// Output: Hello World
Declaration and Initialization of StringBuilder in C#
In C# the declaration and initialization of the StringBuilder are the same as the class.
StringBuilder sb = new StringBuilder();
//or
StringBuilder sb = new StringBuilder(“Hello World”);
In the above code, sb
is the object of the StringBuilder class.
In C#, we can create a new instance of the StringBuilder class by passing the value in the constructor
Setting the capacity and length of the StringBuilder
In C# StringBuilder allows us to set the maximum number of characters it can hold. After the maximum capacity is reached, a new space for the StringBuilder is allocated in the heap.
StringBuilder sb = new StringBuilder();
sb.Capacity = 10;
//or
StringBuilder sb = new StringBuilder(10);
//or
StringBuilder sb = new StringBuilder(“Hello World”, 10);
C# StringBuilder Methods
The following are some commonly used methods of the StringBuilder
class:
C# StringBuilder Append and AppendLine
Method
In C# we use the Append method to add a new text or string at the end of the string represented by the StringBuilder. The AppendLine
method appends the string with a new line at the end of the string.
Example:
The following are the sample code example:
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.AppendLine("World");
//Text append with a new line
sb.AppendLine("This is a new Line");
Console.WriteLine(sb);
Console.ReadLine();
}
}
/* Output:
Hello World
This is a new Line
*/
StringBuilder AppendFormat Method
In C# we can use the AppendFormat method to format the input string into a specified format. which can append at the end of the string represented by the StringBuilder.
In the below example, we are using the AppendFormat method to place an integer value formatted as a currency ($) value.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Total amount: ");
int amount = 250;
sb.AppendFormat($"{amount:C} ");
Console.WriteLine(sb);
Console.ReadLine();
}
}
// The example displays the following output:
// Total amount: $250.00
C# StringBuilder Insert Method
In C# the Insert method adds a string or an object to a specified position in the StringBuilder object.
Here we are inserting a word into the sixth position of a StringBuilder object.
The following are the sample code example.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Hello Shekh");
sb.Insert(6," Mr. ");
Console.WriteLine(sb);
Console.ReadLine();
}
}
// The example displays the following output:
// Hello Mr. Shekh
StringBuilder Remove Method
In C# the Remove method of StringBuilder removes the string at the specified index with a specified length.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Hello Shekh");
sb.Remove(5,6);
Console.WriteLine(sb);
Console.ReadLine();
}
}
// The example displays the following output:
// Hello
StringBuilder Replace Method
In C# the Replace method of the StringBuilder replaces all occurrences of a specified string within the StringBuilder object by a specified replacement string.
Example:
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Hello Shekh ?");
sb.Replace("?","!");
Console.WriteLine(sb);
Console.ReadLine();
}
}
// The example displays the following output:
// Hello Shekh !
Use of Indexer in StringBuilder
In C# we can use the indexer with StringBuilder to get or set characters at the specified index.
In the below example, we are getting all the characters from the StringBuilder using for loop.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Hello Shekh");
for(int index=0; index <sb.Length; index ++)
{
Console.Write(sb[index]);
}
Console.ReadLine();
}
}
// The example displays the following output:
// Hello Shekh
Convert StringBuilder to String
In C# we can convert a StringBuilder object to a string by using the below two methods.
-
- StringBuilder.ToString()
- Convert.ToString(StringBuilder)
Program to convert a StringBuilder object to a string.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.Append("Shekh");
//Convert StringBuilder to string
Console.WriteLine(Convert.ToString(sb));
//or
// Console.WriteLine(sb.ToString());
Console.ReadLine();
}
}
// The example displays the following output:
// Hello Shekh
References: MSDN- StringBuilder in C#
Summary:
In this article, we talked about the difference between String and StringBuilder with multiple examples.
To sum up, when working with sequences of characters in C#, it is important to consider whether you need to modify the string or not. If you only need to read or compare strings, it is more efficient to use a string, as it is an immutable object. However, if you need to build or modify a string repeatedly, you should use a StringBuilder, as it is a mutable object that is more efficient for this purpose. It is important to choose the right type for your needs to ensure that your code is as efficient as possible. Keep in mind that StringBuilder may use more memory than strings in some cases.
I hope this post was helpful and enjoyable. If you have any questions or suggestions, please feel free to leave a comment.
FAQs
The following are some common questions and answers about strings and StringBuilder in C#:
Q: What is a string in C#?
A: A string in C# is an immutable object that represents a sequence of Unicode characters. This means that once a string is created, it cannot be modified.
Q: What is a StringBuilder in C#?
A: A StringBuilder in C# is a mutable object that represents a modifiable string of characters. It is designed for situations where we need to build or modify a string repeatedly.
Q: When should I use a string and when should I use a StringBuilder in C#?
A: You should use a string
when you need an immutable object to hold a sequence of characters. You should use a StringBuilder
when you need to build or modify a string repeatedly, as it can be more efficient than using strings for this purpose.
Q: Can you use a StringBuilder to hold a large amount of text?
A: Yes, you can use a StringBuilder
to hold a large amount of text. However, keep in mind that StringBuilders are mutable objects, so they may use more memory than strings in some cases.
Q: Can we convert a StringBuilder to a string?
A: Yes, we can convert a StringBuilder to a string using the ToString
method.
For example:string str = sb.ToString();
.
Recommended Articles:
- Top 10 Difference between interface and abstract class In C#
- C# List Class |Top 12 Amazing Generic List Methods
- Exception Handling in C#| Use of try, catch and finally block
- C# Enum
- C# extension methods with examples
- Properties In C# with examples
- IEnumerable Interface in C# with examples
- URL vs URI: The Ultimate Guide to Understanding the difference between URL and URI
- Constructors in C# with Examples
- C# Dictionary
- Readonly vs const in C#
- Difference between SortedList and SortedDictionary in C#
- Jump Statements in C# (Break, Continue, Goto, Return, and Throw)
- Is vs As operator in C#: Understanding the differences between is and as operator in C#
- Singleton Design Pattern in C#: A Beginner’s Guide with Examples
- SOLID Design Principles in C#: A Complete Example
- Difference Between Array And ArrayList In C#: Choosing the Right Collection - May 28, 2024
- C# Program to Capitalize the First Character of Each Word in a String - February 21, 2024
- C# Program to Find the Longest Word in a String - February 19, 2024