You can read all the C# performance tips from the following links,
- C# Programming Performance Tips - Part One - String Split
- C# Programming Performance Tips - Part Two - String Equals
- C# Programming Performance Tips - Part Three - Adding Strings
- C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()
- C# Programming Performance Tips - Part Five - List.Count() Vs List.Count
- C# Programming Performance Tips - Part Six - Array Length
Here, we will do the benchmarking for string interpolation, string format, string concat, and string builder.
string str = "Akshay";
string str1 = " Patel";
string result = string.Empty;
Stopwatch s1 = new Stopwatch();
String Interpolation
s1.Start();
result = $ "{str} {str1} is an author.";
Console.WriteLine("String Interpolation " + s1.ElapsedTicks.ToString());
String.Format
s1.Restart();
result = string.Format("{0},{1} is an author.", str, str1);
Console.WriteLine("String.Format " + s1.ElapsedTicks.ToString());
String.Concat
s1.Restart();
result = string.Concat(str, str1, " is an auther");
Console.WriteLine("String.Concat " + s1.ElapsedTicks.ToString());
StringBuilder
s1.Restart();
StringBuilder sb = new StringBuilder();
sb.Append(str);
sb.Append(str1);
sb.Append(" is an auther");
result = sb.ToString();
Console.WriteLine("String Builder " + s1.ElapsedTicks.ToString());
Console.ReadLine();
We have adopted four different ways to add two string variables. Let’s see the benchmarking result.
Benchmarking result suggests going with String.Concat.