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