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.. ";
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("Welcome to Strings.. ");
sbTest.Append("This is a demo.. ");
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.