What is the Main difference between String and
StringBuilder and why do we use StringBuilder.
Answer Posted / k.saisagar
In Dot Net there will be many cases where in we need to operate on strings and first thing we remember is using system.String but there are certainly many points we need to remember and consider before we operate on strings.
1) Performance.
2)how many times we need to concatenate.
Lets take an example for concatenate five strings.
EX 1. Using System.String
System.String str =“My Name is dilip”;
str += “and i am”; str += “working on “;
str += “Post of “;
str += “difference between string and string builder”;
Response.Write(str);
and the expected output well you probably guessed it right
“My Name is dilipand i amworking on Post of difference between string and string builder”
Now what has happed? yes the important question now how many times we have appended the str variable those number of times string was created in memory location and abandoned when a new string is created and later waiting for garbage collection.
This leads to memory wastage and degradation of performance because string are immutable(that means any change to string causes a runtime to create a new string and abandon old one).
Think about the situation where in u need to work on 100 or more strings????
Dot Net has answer for it in the form of System.Text.StringBuilder class
EX2. Same Example using StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append( “My Name is dilip”);
sb.Append( “and i am”);
sb.Append( “working on “);
sb.Append( “Post of “);
sb.Append( “difference between string and string builder”);
and the output is same as previous
“My Name is dilipand i amworking on Post of difference between string and string builder”
But this time there was only one string created in memory dynamically and modified as we append the new string, by this there is not much garbage collection and also helps improve performance. Append is taken only for example there are a lot of other functions which are just waiting for you to invoke.Happy coding.
| Is This Answer Correct ? | 1 Yes | 0 No |
Post New Answer View All Answers
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
How to use session under class file of APP_Code folder?
Which is more efficient for loop or while loop?
What is lazy in c#?
Is there an equivalent to the instanceof operator in visual j++?
What are boxing and unboxing?
What’s a strong name?
What do you mean by saying a "class is a reference type"?
What is a callback c#?
I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all constructors to private?
What is assembly c#?
What is dll hell, and how does .net solve it?
Describe ado.net?
What is the Signification of the "new " keyword in C#? example
Name which controls do not have events?