Tech News

Difference Between StringBuilder and String?

String:


1.Its a class used to handle strings.
2.Here concatenation is used to combine two strings.
3.String object is used to concatenate two strings.
4.The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted
5.That is why  “Strings are immutable”.

6. It means that you can’t modify string at all, the result of modification is new string. This is not effective if you plan to append to string.
7.A String (System.String) is a type defined inside the .NET framework. This means that every time you do an action to an System.String instance, the .NET compiler create a new instance of the string.
8. Slower.


//for example: 
string str = “hello”//Creates a new object when we concatenate any other words along with str variable it does not actually modify the str variable, instead it creates a whole new string. 
str = str + ” to all”;Console.WriteLine(str);
String Builder:


1.This is also the class used to handle strings.
2.Here Append method is used.
3.Here, Stringbuilder object is used.
4.Insertion is done on the existing string.
5.Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed.
6.StringBuilder is mutable. It can be modified in any way and it doesn’t require creation of new instance. When work is done, ToString() can be called to get the string.

7.A System.Text.StringBuilder is class that represent a mutable string. This class provide some useful method that make the user able to manage the String wrapped by the StringBuilder. Notice that all the manipulation are made on the same StringBuilder instance.
8. Faster.


//for example: 

StringBuilder s = new StringBuilder(“Hi”);s.Append(” To All”);Console.WriteLine(s);


………………………………………………………………………………………………………………………………………………

Instead of doing this:
String x = "";
x += "first ";
x += "second ";
x += "third ";
you do
StringBuilder sb = new StringBuilder("");
sb.Append("first ");
sb.Append("second ");
sb.Append("third");
String x = sb.ToString();
the final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x