Thursday, April 10, 2008

String vs. StringBuilder

String type is immutable. Immutable basically means "cannot be changed". Consider the following code:
   1:  string name = "Mark";
   2:  name += " Moeykens";
   3:  name = string.Format("Mr. {0}", name);
On line 1 a string was assigned "Mark". On line 2 "Mark" was thrown away and a new string was created, "Mark Moeykens". On line 3 "Mark Moeykens" was thrown away and a new string, "Mr. Mark Moeykens" was created. Since strings are immutable, a new place in memory has to be created everytime the value changes. StringBuilder manipulates strings much more efficiently. In cases where you have a lot of string manipulation, StringBuilder would be a better candidate.
StringBuilder sb = new StringBuilder();
sb.Append("Mark");
sb.Append(" Moeykens");
sb.Insert(0, "Mr. ");
Notes
  • StringBuilder still outperforms string when concatenating just two strings.
  • There is not much of a difference in time (milliseconds) until you go over about 10,000 concatenations
  • StringBuilder is a good choice for applications that need to scale, like web applications.

More Info: MSDN: Using the StringBuilder Class