The truth about string concatenation performance...

time to read 1 min | 112 words

Here is a riddle, what is faster?

  • string str = "Id: " + i;
  • string str = string.Format("Id: {0}", i);
  • string str = new StringBuilder().Append("Id: ").Append(i).ToString();

If you guess StringBuilder or string.Format, you are mistaken. Over 10 million iterations, the simple "Id: " + i finished in 4.7 seconds, StringBuilder in 5.7 seconds and string.Format in 7.6 seconds.

The reason for that is that the compiler can optimize the + operator to a call to string.Concat, and it does it quite often when you have several parameters. The optimizations of StringBuilder only shows up if you have several concatenations, or if you are using it on more than a single expression.