DEV Community

Cover image for String Vs StringBuilder In C#
Tural Suleymani
Tural Suleymani

Posted on

String Vs StringBuilder In C#

As we know, string class is for storing text type information in RAM. The information storage capacity of the string type variable is 2GB. That is, we can store information of any size (less than 2GB) in the RAM using a string.

What is the disadvantage of the String class that we need to use the StringBuilder class?
The only minus of the String class is that it is immutable!! Yes, if you assign information to any variable declared in the string class type, that information cannot be changed later!

String Vs StringBuilder In C#

Yes, the point is that most of you think of such a piece of code.

stringbuilder mem
Yes, the point is that most of you think of such a piece of code.

//define a variable
string str = "some data";
//the old information in str will live without any reference in memory!!
//new data assigned to str!!!
str = "data changed";
Enter fullscreen mode Exit fullscreen mode

By doing so, you think the string has changed. The string type is immutable.

In the code example above, the variable str is first declared and some data is written to it. The catch here is that if we assign another value to the str variable, the old value is not overwritten, as is the case with other variable types!! In other words, "some data" is stuck somewhere in the Operating memory and is not deleted. And the str variable just keeps a link to the memory area where the new information is located!!

Now consider that when you concatenate a value to a string variable using loop operations, you are dumping memory excessively.

static string ReverseString(string value) {
    string reversedData = String.Empty;
    for (int i = value.Length - 1; i >= 0; i--) {
        reversedData += value[i];
        Console.WriteLine($ "New data stored separately as '{reversedData}'");
    }
    return reversedData;
}
Enter fullscreen mode Exit fullscreen mode

The code example above is a very poorly written code because it does not use memory space optimally. Let's consider what happens in memory.

string usage memory representation
So our above method is used to reverse all string data. The algorithm works, but we overload the memory space unnecessarily. We call our method and pass the word data changed to it. During the first cycle, the letter d is assigned to the reversed data variable. During the second period, the memory area with the letter d is no longer manipulated!!! Because the string is immutable. This time, only a new memory area is allocated and the ‘de’ phrase is stored there. In the 3rd period, this time, the memory area containing the de phrase is manipulated, that is, no overriding occurs, a new memory location is allocated again, and this time the deg expression is stored there. As we can see, this process continues until the end, and useless data without a link is created in memory. Depending on the size of the parameter passed, the memory can be more or less dirty. When we execute the method, we get such a result.

So, the old memory area is not overwritten in the cycle process, but a separate memory area is allocated for each concatenation!

The StringBuilder class was created to solve this memory problem.

stringbuilder as a hero
Through the StringBuilder class, we solve the problem of allocating separate memory space to each variable. StringBuilder allocates only 1 dynamically expanding memory area and uses only 1 memory area during each concatenation. This prevents free memory allocation. We can solve the task we solved above with string in a more correct form with StringBuilder like this,

static string ReverseStringWithBuilder(string value) {
    StringBuilder reversedData = new StringBuilder();
    for (int i = value.Length - 1; i >= 0; i--) {
        reversedData.Append(value[i]);
        Console.WriteLine($ "New data stored separately as '{reversedData}'");
    }
    return reversedData.ToString();
}
Enter fullscreen mode Exit fullscreen mode

Want to dive deeper?

Every 5 days, I share my senior-level expertise on my 'DecodeBytes' YouTube channel, breaking down complex topics like .NET, Microservices, Apache Kafka, Javascript, Software Design, Node.js, and more into easy-to-understand explanations. Join us and level up your skills!

Top comments (0)