DEV Community

Cover image for String and StringBuilder in C#: Key Differences Explained
Jin Vincent Necesario
Jin Vincent Necesario

Posted on

String and StringBuilder in C#: Key Differences Explained

Introduction

In this post, we’ll explore the key differences between String and StringBuilder in C# so that you can optimize string operations in your projects effectively.

Before continuing, I recommend reading my C# Corner article, "Playing with C# Strings Instance Methods," which I wrote six years ago.

It remains closely related to this topic.

Let’s get started.

What is a string?

Bear in mind that a string is a collection, or array, of read-only characters.

In other words, it is a sequence of characters used to represent text and an object type in the System namespace.

Another thing, strings are immutable, meaning that once they are created, their content cannot be changed directly.

What is Immutability?

Within the context of C# and .NET, immutability design prevents accidental modification of shared data.

Understanding immutability, let’s say an object is considered immutable if its internal state cannot change after it is created. If changes are needed, a new object must be created rather than modifying the existing one; this applies to strings as well.

Okay, so we don't get confused, let's use an example.

[Fact]
public void String_Should_Not_Be_Changed_When_Concatenated()
{
    //arrange
    string original = "dev.to rocks!";

    //act 
    string modified = original + " but it is not the only one!";

    //assert
    Assert.Equal("dev.to rocks!", original);
    Assert.Equal("dev.to rocks! but it is not the only one!", modified);
}
Enter fullscreen mode Exit fullscreen mode
[Fact]
public void String_Concatenation_Creates_New_Instance()
{
    string a = "Hello";
    string b = a;

    string c = a + "!";

    Assert.Same(a, b);      // same reference initially
    Assert.NotSame(a, c);   // new string instance created
}
Enter fullscreen mode Exit fullscreen mode

What is StringBuilder?

If a string is immutable, then StringBuilderis the opposite: it is mutable.

StringBuilder represents a mutable sequence of characters, allowing its content to be changed.

The StringBuilder class provides this functionality and is available in the System. Text namespace.

Moreover, once you have created a StringBuilder object, you can perform certain operations like insert, replace, or append without creating a new instance every time you do it. Plus, it will update the string in a single place in memory and won’t allocate new space.

[Fact]
public void StringBuilder_Is_Mutable()
{
    // Arrange
    var sb1 = new StringBuilder("Hello");
    var sb2 = sb1; // Same object

    // Act
    sb1.Append(" World");

    // Assert
    Assert.Equal("Hello World", sb1.ToString());
    Assert.Equal("Hello World", sb2.ToString());
    Assert.Same(sb1, sb2);
}
Enter fullscreen mode Exit fullscreen mode
[Fact]
public void Append_Should_Modify_Existing_Instance()
{
    // Arrange
    var sb = new StringBuilder("Hello");

    // Act
    sb.Append(" World");

    // Assert
    Assert.Equal("Hello World", sb.ToString());
}
Enter fullscreen mode Exit fullscreen mode

Why are Strings immutable while StringBuilder is mutable?

Making strings immutable has several advantages; it provides automatic thread safety. It makes strings behave like an intrinsic type in a simple, effective manner, which also allows for extra efficiencies at runtime and huge security advantages, since it’s impossible for a third-party API call to change your strings.

That’s why StringBuilder was added to address the disadvantage of immutable strings. The runtime construction of immutable types causes a lot of Garbage Collector (GC) pressure and is inherently slow.

Deciding between String and StringBuilder

Here is a practical guide for choosing between String and StringBuilder, designed to help you understand their strengths and feel more in control of your code decisions.

Use a string for short, static, or rarely changing text.
Choose String when performance is not critical, and simplicity is preferred.

Use StringBuilder when building large or complex strings, especially with frequent modifications, to optimize speed and memory and make your code more efficient.

Summary

In this post, String and StringBuilder both handle text in C#, but as you can see, they have different uses in different scenarios.

As we have discussed, a String is immutable, meaning its value cannot be changed once created; any modification creates a new String object (a new instance). This provides benefits such as thread safety, reliability, and security, but it can affect performance when you intend to change. So, imagine the thousands of strings created at once.

While StringBuilder, on the other hand, is mutable and allows text to be modified directly through operations such as append, insert, and replace.
That’s why you should already remember to use String for simple, short, or rarely changing text, and choose StringBuilder when working with large, complex, or frequently modified strings where performance and memory efficiency matter.

Stay tuned for more (keep visiting our blog and share this with your friends, colleagues, and network).

Until next time, happy programming!

Please don’t forget to bookmark, like, and comment. Cheers! And thank you!

References

https://dev.to/shreyans_padmani/string-vs-stringbuilder-in-c-understanding-the-difference-for-better-performance-3ge5
https://www.c-sharpcorner.com/article/immutability-the-secret-weapon-for-reliable-c-sharp-applications/
https://stackoverflow.com/questions/2365272/why-net-string-is-immutable
https://www.c-sharpcorner.com/blogs/difference-between-string-and-stringbuilder-in-c-sharp1

Top comments (0)