StringBuilder vs String

String vs String Builder

While manipulating strings, we generally tend to use the string instance. Using the string instance is easy in terms of implementation but sometimes, manipulating the string can be a bit heavy in terms of performance.

String

A string instance is mutable i.e. for every string created, a new block of memory is allocated to the created string. When we try to modify that string by either appending another string, replacing some characters or by any other means, it will allocate new memory blocks for the modified string and change the reference of the string variable to the new memory block assigned. The older memory block that was originally assigned is left for garbage collection.

When we create a string like:

string name = "TEST";

The string variable named name holds the reference to this memory block when we assign it the value TEST like the image below:

 

memory allocation of a string variable

When we try to modify the string, it will assign new blocks of memory for the updated string & the reference too memory blocks will be updated as in the image below.

name += "1";

 

memory allocation of a modified string variable

The memory blocks occupied by the older string will be left for garbage collection.

This operation is easy to implement at the coding level. When it comes to frequently updating the string, the process of assigning new memory blocks and changing the reference to the newer blocks increase the performance cost of the program.

To prevent performance issues, we use the String Builder class.

String Builder

String builder is a class from System.Text namespace that solves the above issue of memory allocation for every modification of string. Using String Builder allows preventing creating a new string instance every time we modify an existing string. Instead, the modify the string in their existing memory blocks.

We create a new instance if string builder using the following syntax:

StringBuilder name = new StringBuilder("TEST");

Creating a string with string builder allocates some memory blocks for the string as in the image below.

memory allocation of a string builder

When we want to modify the string, we use the methods of the string builder class.

To append a new string, we use the append method like

name.append("1);

memory allocation of a modified string variable with string builder class

On modifying the string created with StringBuilder class, new memory isn’t allocated to the new string created after appending. Instead, the existing memory blocks are extended to accommodate the new string. In this way, a new instance isn’t created everytime we modify the string but the existing instance is modified this reducing the overhead of creating a new instance for every modification.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.