Search This Blog

Wednesday 23 July 2014

String vs String Builder

String
String Builder
String objects are immutable, which means that once they are created they cannot be changed. When we use one of the methods of the String class, we create a new string object.StringBuilder are mutable class, which means whenconcatenate any text to the variable it allows us to modify the original value without creating a new object.
Here concatenation is used to combine two strings.Here Append method is used.
String object is used to concatenate two strings.Stringbuilder object is used.
The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deletedInsertion is done on the existing string.
Less efficientStringBuilder is more efficient for large amounts of string manipulations


String

String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.


Example
string str = "hi";
// create a new string instance instead of changing the old one
str += "test";
str += "help";


String Builder

String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.

Example

StringBuilder sb = new StringBuilder("");
sb.Append("hi");
sb.Append("test ");
string str = sb.ToString();



- See more at: http://www.f5debug.net/post/2011/11/01/Interview-Questions-and-Answers-on-Net-Framework-OOPS-ASPNet-CNet-SQL-Server-WCF-Series-Part-14.aspx#Question4

No comments:

Post a Comment