Sunday, August 15, 2010

String vs StringBuilder

1- String
System.string is immutable in .Net Framework. That means that any change to a string cause the runtime to create a new string address in memory and abandon the old one.

Example:

string s = "Hello"; //(1)
s += "World"; //(2)
s += "Programming"; //(3)


After running this code, only the last string has reference (3); the other are disposed during garbage collection.


There are several ways to avoid temporary strings:
  • Using Concat, Join, Format methods
  • Using StringBuilder


2- StringBuilder
System.StringBuilder is mutable string, which create only one reference address in memory during the running application. By default, the constructor creates a 16-byte buffer. You can also specify an initial size and a maximum size if you like.

Example:

StringBuilder sb = new StringBuilder(50);
sb.Append("Hello");
sb.Append("World");
sb.Append("Programming");


0 comments:

Post a Comment