Back
Close

The Difference between String and StringBuilder in C#

AramT
54.4K views

A String is basically an immutable sequence of characters. Each character is a Unicode character in the range U+0000 to U+FFFF.

Immutable means that its state cannot be modified after it is created.

Thus, if you assign a value to a string then reassign. The first value will stay in the memory and a new memory location will be assigned to accept the new value.

Let’s take these string allocations for example:

string string1  = "Tech";
string string2  = "io";
string string3 = "";
string3 = string1 + "." + string2;

This leads to 4 memory addresses to be allocated: Tech, io, [EmptyString] , and the Concatenation between tech , [dot] and io

When using the above method for a specific purpose or when you know the number of strings to be concatenated at compile time will be few, then the wasted memory will be negligible, however, this will generate a big issue when in a loop with lots of iterations, where a string is adding (Concatenating) to itself another string or value, it is just constantly reallocating, in other words, it is copying to a new memory location when the memory manager can’t expand the requested amount in place. At this point, the amount of memory required (or wasted) and the processing time used for the creation of the numerous objects may become a bottleneck in the application.

This case is mostly common when, for instance, dynamically generating a TABLE and its content, or building an XML document. With this type of scenario in mind, Microsoft included the StringBuilder class in .NET.

By the way, you might wonder what is the difference between string and String, they both refer to the string type. string, in its small letter form, is only an alias to the String class in C#.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io