Strings

  • DO use the System.Text.StringBuilder class for of concatenating a large number of strings.

    In C#/.NET, strings are immutable. So, every time you perform some operations that look like they’re changing a string, they’re creating a new one instead. Such operations include methods like Replace and Substring, but also concatenation.

    Beware of concatenating a large number of strings, especially inside a loop

    So, the tip here is simple—beware of concatenating a large number of strings, especially inside a loop. In situations like this, use the System.Text.StringBuilder class, instead of using the “+” operator. That will ensure that new instances aren’t created for each part you concatenate.

    • DO set the Capacity of StringBuilder to reduce allocations

      An important characteristic of a StringBuilder is its capacity property. The capacity property represents the number of characters in the current instance that are allocated internally to store information in memory.

      While using StringBuilder, you may configure the capacity property of a StringBuilder instance to optimize efficiency. If you know the length of the string you are going to create, you may set the initial capacity of the StringBuilder instance when creating it. This will significantly reduce memory allocation and hence improve application performance.

    • DO use a pool of StringBuilder Instances

      You can take advantage of a reusable pool of StringBuilder instances to improve your application’s performance. This can be achieved by reusing an instance of a StringBuilder from the pool. The following C# code snippet shows how you can do this:

      var pool = new DefaultObjectPoolProvider().CreateStringBuilderPool();
      
      for (var i = 0; i < 100; i++) {
        var builder = pool.Get();
        builder.Append("Hello World" + i);
        builderPool.Return(builder);
      }
      
    • DO reduce Allocations using StringBuilderCache

      You can reduce allocations further by using an internal class named StringBuilderCache. Surprisingly, very few people know that this class has been a part of .NET Framework for a very long time. It is also available in the newer versions of .NET Framework, and .NET Core. The StringBuilderCache class works by creating an instance of the StringBuilder when requested by the calling code and then leasing it for use. Your calling code should use this instance and return it back when done. As a result, you would be using just one instance of the StringBuilder in most cases.

      The following code snippet shows how the StringBuilderCache can be used in C#:

      string str = StringBuilderCache.GetStringAndRelease(stringBuilderInstance);
      
  • DO use AppendJoin for joining strings

    When you are joining strings in your application, make sure that you leverage StringBuilder.Join and not the String.Join method. The StringBuilder.Join method, when used on multiple strings, will reduce allocations considerably.

    The following C# code example illustrates how the AppendJoin method can be used:

    public string JoinStrings()
    {
        var builder = new StringBuilder();
        for (int i = 0; i < 100; i++)
        {
           builder.AppendJoin("Joining", ' ', "Strings", ' ',
           "Is", ' ', "Costly");
        }
      return builder.ToString();
    }
    
  • AVOID Culture-sensitive comparisons.

    AUnless you have a reason to use culture-sensitive comparisons, always use ordinal comparisons instead. While it doesn’t make much of a difference with en-US culture because of internal optimizations, the comparisons get one order of magnitude slower with other cultures (up to 2 orders of magnitude on Linux!). As string comparisons are a frequent operation in most applications, it quickly adds up.

Learn More