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
Is null == null c#?
Is object an int c#?
Why do we need properties in c#?
How long does a loop recorder procedure take?
List down the fundamental oop concepts?
List down the access modifiers available in c#?
Is std :: string null terminated?
What is a callback c#?
How does the lifecycle of Windows services differ from Standard EXE?
Explain About .Net remoting
What are the different types of classes?
What is a console file?
Can you see a loop recorder?
Does c# support parameterized properties?
Where do we set the min and max pool size for connection pooling?