0

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?

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?

Thanks for your time in advance.

3
  • Read the unaccepted answer (the one without the checkmark) to this question Commented Aug 10, 2018 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 Commented Aug 10, 2018 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. Commented Aug 10, 2018 at 17:50

2 Answers 2

0

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 = 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.