Microsoft Interview Question
Software Engineer in Testsstring can hold strings/char array
stringbuilder can keep on adding strings which later can be converted into one single string
Though both of them can hold and concatenate strings,
string is optimized for only few concatenations, so when we have to keep on appending large no of strings into one string, stringbuilder can be used for more efficiency.
strings are immutable.
I don't think "strings are optimized for a few concat" is accurate.
Each time you do a string concat, you end up creating a new string and doing a memory copy, which can get rather inefficient quickly.
Stringbuilder gets rid of that problem.
In C# I this statement is correct:
"strings perform better for a few concatenations when compared to StringBuilder".
I had good discussion with my leas on this topic and then I ran some test to prove the above statement, (Small String Concatenations upto 50 concatenation string can beatStringBuilder in performance obviously not in memory )
String is immutable
StringBuilder is mutable - when you forsee updating your string frequently, use string builder.
"The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop."
Strings objects are immutable. Means we can not modify strings. Whenever we try to modify string object a new object is created internally. To understand the immutability of string we can take an example of string addition
String str="XYZ";
System.out.println(str.concat("ABC"));
System.out.println(str);
Here output of 1st sop will be XYZABC whereas for next sop output will be XYZ.
It indicates that a new string is created while we did concat on str but str is not changed.
And StringBuilder and StringBuffer are mutable.
Now difference between StringBuilder and StringBuffer. Although functionality wise there is no difference except StringBuffer are synchronized. If you are developing single threaded app and your string is getting modified frequently then to get best performance StringBuilder is best option in comparison to StringBuffer. Since StringBuffer is synchronized to its bit slow.
String: Immutable
- Anonymous October 06, 2009StringBuilder: Mutable + No guarantee of synchronization
StringBuffer: Mutable + Synchronized