There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Sunday, September 16, 2007

Efficient way of combining Strings using StringBuilder Class

In C#.NET, when combining strings, we often tend to combine as follows. This article discusses an efficient way of doing it.

public string createContent()
{
string sMessage = string.Empty;
sMessage += "Introduction.. ";
sMessage += "Welcome to Strings.. ";
sMessage += "This is a demo.. ";
return sMessage;
}

As you know String is a refernce type, and each time sMessage will be assigned by a value, but we only use the last assigned value. The others will be disposed by the GC. To avoid unneccasary garbage collection we could use StringBuilder. This is how we could use it.

public string createNextContent()
{
StringBuilder sbTest = new StringBuilder();
sbTest.Append("Introduction.. ");
sbTest.Append("Welcome to Strings.. ");
sbTest.Append("This is a demo.. ");
return sbTest.ToString();
}

StringBuilder creates a buffer of 16bytes long by default and grows as needed. It is possible to specify the initial size and the maximum size as well.