C# String Concatenation Performance
September 24, 2014 Leave a comment
Out of curiosity, I’m trying to find out which string concatenation method would be the fastest (most optimised) when writing C# applications.
There are a few ways to do that.
var str = “Foo” + ” ” + “Bar”;
var str = string.Format(“{0} {1}”, “Foo”, “Bar”);
StringBuilder strBuilder = new StringBuilder();
strBuilder .Append(“Foo”);
strBuilder .Append(” “);
strBuilder .Append(“Bar”);
var str = strBuilder .ToString();
It is quite clear at StringBuilder adds extra overhead for the concatenation. Therefore, I’m going to demonstrate only the performance between the first two options.
This example uses the code from StackOverflow.
Stopwatch s = new Stopwatch();
var p = new { FirstName = “Bill”, LastName = “Gates” };
int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;
string result;
s.Start();
for (var i = 0; i < n; i++)
result = (p.FirstName + ” ” + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
result = string.Format(“{0} {1}”, p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();Console.Clear();
Console.WriteLine(n.ToString() + ” x result = string.Format(\”{0} {1}\”, p.FirstName, p.LastName); took: ” + (fElapsedMilliseconds) + “ms – ” + (fElapsedTicks) + ” ticks”);
Console.WriteLine(n.ToString() + ” x result = (p.FirstName + \” \” + p.LastName); took: ” + (cElapsedMilliseconds) + “ms – ” + (cElapsedTicks) + ” ticks”);
Console.Read();
The result
- String Concatenation: 61ms – 204,570 ticks
- String Format: 173ms – 574,676 ticks
I guess this might be a little bit overkill and I also like a comment from someone (sorry, I really can’t remember who that was) that … at the end of the day, machines are more powerful and it’s best to make the code readable.
So, if you are curious like me, feel free to run the code and experiment this yourself. Credit: StackOverflow!