top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between string and stringbuilder?

0 votes
457 views
What is the difference between string and stringbuilder?
posted Mar 22, 2017 by Sachin

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Strings:
The class System.String enables us to handle strings in C#.The class System.String enables us to handle strings in C#.

Strings are Immutable
The string class has an important feature – the character sequences stored in a variable of the class are never changing (immutable). After being assigned once, the content of the variable does not change directly – if we try to change the value, it will be saved to a new location in the dynamic memory and the variable will point to it.

When we initialize a variable of type string with a string literal, the memory checks invisibly for us whether this value already exists. If the value already exists, the new variable is simply pointed to it. If not, a new block of memory is allocated, the value is stored in it and the reference is changed to point to the new block. The string interning in .NET is possible because strings are immutable by design and it is not likely that the memory block referenced by several string variables will simultaneously be changed by someone.

StringBuilder

StringBuilder are mutable.

The StringBuilder class is an implementation of a string in C#, but different than the class String. Unlike the already familiar for us strings, the objects of the StringBuilder class are not immutable, namely edit operations do not require creating a new object in the memory. This reduces the unnecessary transfer of data in memory when performing basic operations such as string concatenation.

StringBuilder keeps a buffer with a certain capacity (16 characters by default). The buffer is implemented as an array of characters that is provided to the developer by a user-friendly interface – methods that quickly and easily add and edit elements of the string. At any moment part of the characters in the buffer are used and the rest stay in reserve. This allows the addition to work very quickly. Other operations also operate faster than the class string, because the changes do not create a new object.

answer Mar 22, 2017 by Shweta Singh
...