StringBuilding in C#

Programming C#

Strings are a vital part of applications and building strings can take up a lot of time, along with also causing a performance lag in the applications. There are many ways in which you can build strings in C# programs. Consider this console application:

class Program
{
static void Main(string[] args)
{
SomeStringBuildMethod("Max K. Smith", "36");

Console.WriteLine("Done.");
Console.ReadLine();
}

private static void SomeStringBuildMethod(string name, string age)
{
string str = string.Empty;

// option #1
str = "Name: " + name + ", Age: " + age;
Console.WriteLine(str);

// option #2
str = string.Format("Name: {0}, Age: {1}", name, age);
Console.WriteLine(str);

// option #3 - best possibility before C# 6.0
var builder = new StringBuilder();
builder.Append("Name: ");
builder.Append(name);
builder.Append(", Age: ");
builder.Append(age);
str = builder.ToString();
Console.WriteLine(str);

// option #4 - best possibility C# 6.0+
str = $"Name: {name}, Age: {age}";
Console.WriteLine(str);
}
}

Although many tend to option #1 this is by far the worst choice.

Strings in C# are immutable. This means that if you update their values, they are recreated and previous handles are removed from the memory. This is time consuming. Therefore bad.

String.Format in option #2 seems like a good choice but will be quite hard to mainten as soon as you've got more than a few parameters and need to add an additional one.

StringBuilder as used in option #3 was the best performance choice until the release of C# ver 6.0 - but yes, one has to type in much more code then in option #1.

The string interpolation operator $ introduced with C# 6.0 provides you with the facility of performing the string concatenation in best possible way, definitely killing options 1 and 2.

Under the hood, string interpolation uses String.Format - this brings a cleaner look to your programs when someone else is reading the code, along with increasing performance.

But for larger strings one will allways have to fallback to StringBuilder.