Thursday 27 June 2013

What is the difference between String and stringBuilder in ASP.NET ?

String

1.Its a class used to handle strings.
2.Here concatenation is used to combine two strings.
3.String object is used to concatenate two strings.
4.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 deleted
5.That is why  "Strings are immutable".
6. Slower


Example  :

 string s = string.Empty;
for (i = 0; i < 1000; i++) {
  s += i.ToString() + " ";
}


String Builder
1.This is also the class used to handle strings.
2.Here Append method is used.
3.Here, Stringbuilder object is used.
4.Insertion is done on the existing string.
5.Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed.
6. Faster


Example :


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

No comments:

Post a Comment