Effectively use StringBuilder to gain Performance

High performance of application is implicit requirement, no one states it, and however it’s there and supposed to be taken care of. Here is my first blog on StringBuilder that hopefully help you to sharpen your skills and become an excellent C# developer. (This is written after so many observations from code reviews) and from my personal experiences.

Using StringBuilder is the most recommended way to concatenate large chunks of strings , mostly this happens in loop. It is the best approach to take, and despite this I have seen many developers not to follow this practice.

I have also seen developer’s instantiating StringBuilder in an inefficient ways too. You should effectively use StringBuilder to gain performance, and below are the guidelines for some efficient ways to use StringBuilder & get some performance.

  • Always try to instantiate StringBuilder with some default value or capacity
  • Use in large loops or at places where most of the concatenations are happening
  • Use the same instance of StringBuilder in all methods that construct a single string

Example code:


Can you guess why I have used “loop.ToString(CultureInfo.InvariantCulture)” in the above example code?

Related readings:



Effectively use StringBuilder