Benefits using StringBuilder rather than String during concatenation or String Building [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Benefits using StringBuilder rather than String during concatenation or String Building [duplicate]



This question already has an answer here:



This is the string reversal method in C# that I was investigating:


string s = "This is the way it is.";
string result = string.Empty;

for(int i = s.Length-1; i <= 0; i--)

result = result + s[i];

return result;



Assuming that the strings can get very very long. Why is it beneficial to use Stringbuilder in this case over concatenating to result using s[i] as shown above?


Stringbuilder


s[i]



Is it because both result and s[i] are immutable strings and therefore an object will get created each time both of them are looked up? Causing a lot of objects to be created and the need to garbage collect all those objects?


s[i]



Thanks for your time in advance.



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





Read the unaccepted answer (the one without the checkmark) to this question
– Ken White
Aug 10 at 16:26





StringBuilders are mutable whereas strings are not, if you keep concatenating to a string you have to create an object with more space every time. StringBuilders can be given the correct amount at the start
– G. LC
Aug 10 at 16:26





Thanks Ken & G. LC. The article that you directed me to helped answer my question thoroughly and got me to understand how the temp variables are allocated in memory when calling String rather than StringBuilder.
– Tony Ko
Aug 10 at 17:50




2 Answers
2



NO. Not both of them. Both of strings in this case are immutable. However, look in the for loop, a new result String object is created but not s string object as it is not being updated, we are just accessing it. immediately after the assignment, we have the previous result object illegible for garbage collection as it is loosing reference but not s string object. in the next iterateion, the current new result String object will be garbge collected and so on. had you used string builder, you would have different situation.


result


s


result


s


result


result = result + s[i];



Unlike strings, stringbuilder is mutable. so if your result variable was type of Stringbuilder, new result object would not be created rather the existing one will be updated according to the assignment.


result


result



StringBuilder is mutable. Meaning it does not create new object when modifying it.
You can read more in this page

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered