27 April, 2012

Difference between String and StringBuilder

String and StringBuilder class both are used to handle string.
StringBuilder is an immutable class means that you can insert, append and replace without creating a new StringBuilder instance each time.
String is immutable, each time you perform an operation on the string – you are actually creating a new instance of string to replace the old one.
 So according to the discussion, the StringBuilder is more efficient for operations to manipulate strings.
The most common operation with a string is concatenation. When you use the “String” object to concatenate two strings, the first string is combined to the other string by creating a new instance in the memory and then the old string is deleted.
When you make a “StringBuilder” object for concatenation the Append method is used which is perform insertion operation on the existing string. So, StringBuilder is more efficient in case of large amounts of string manipulation.

Have a look on the following code snippet.
string str = string.Empty;
for (int i = 0; i < 1000; i++) {
  str += i.ToString() + " ";
}

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
  sb.Append(i);
  sb.Append(' ');
}


Now think, which one is faster?  Right! The second one. Because, for the first snippet, every time new instance of string is created and the for the second one, StringBuilder instance is created only at once.

No comments:

Post a Comment