C# interview question :- Why is
stringbuilder concatenation more efficient than simple string concatenation?
This question is one of the favorites question which comes during
c#interviews and the interviewer is not only expecting which one of them is more efficient. But he is also expecting the reason for the same.
In order to understand the same better lets consider the below scenario where we have two lines of code which does string concantenation.
For a simple string concantenation code shown below it will create 3 copies of string in memory.
//The below line of code Creates one copy of the string string str = "shiv"; /* The below line of code creates three copies of string object one for the concatenation at right hand side and the other for new value at the left hand side. The first old allocated memory is sent for garbage collection.*/ str = str + "shiv";
When you use the string builder for concatenation it will create only one copy of the object.
/* The below code uses string builder and only one object is created as compared to normal string where we have 3 copies created*/ StringBuilder objBuilder = new StringBuilder(); objBuilder.Append("shiv");
Ok now summarizing what should we say to the interviewer.
String is immutable. Immutable means once assigned it can not be changed. Thats why it creates more copies of the object as it can not use the same instance.String builder is mutable , in other words the same object will changed rather than creating new objects.
So string builder is more efficient as compared to simple string
See my 300 important c# interview questions and answers