C# Programming Performance Tips - Adding Strings

C# Programming Performance Tips - Adding Strings

You can read all the C# performance tips from the following links,

  1. C# Programming Performance Tips - Part One - String Split
  2. C# Programming Performance Tips - Part Two - String Equals
  3. C# Programming Performance Tips - Part Three - Adding Strings
  4. C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()
  5. C# Programming Performance Tips - Part Five - List.Count() Vs List.Count
  6. 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.

C# Programming Performance Tips - Part Three - img1.png

Benchmarking result suggests going with String.Concat.