Speeding Up The StringBuilder Using An ObjectPool

If you weren’t aware, Microsoft .NET has a type called the ObjectPool that can be used to speed up performance since objects are pooled, instead of creating a new one each time it’s needed. In this article, I will show you how to use it with the StringBuilder.

256 Seconds with dotNetDave

To show you how to use the StringBuilder with an ObjectPool, I have created a new episode of 256 Seconds with dotNetDave.

https://vimeo.com/743169409

The Code

First, create the pool in a field as shown below:

private readonly ObjectPool<StringBuilder> _stringBuilderPool = 
    new DefaultObjectPoolProvider().CreateStringBuilderPool();

To use it, get the StringBuilder from the pool using the Get() as shown below.

var sb = this._stringBuilderPool.Get();

Then use the StringBuilder as normal as shown in this example that simulates concatenating strings from an array.

for (var index = 0; index < this._stringArray.Length; index++)
{
    _ = sb.Append(this._stringArray[index]);
}

When the StringBuilder is no longer needed, return it back to the pool.

_stringBuilderPool.Return(sb);

Benchmark Results

As you can see from the benchmark report for .NET 6, in all cases using the ObjectPool is slightly more performant. The benchmark report for .NET 7 shows similar results.

Speeding Up the StringBuilder Using an ObjectPool

Allocations

There is a difference with the allocations for these three benchmark tests.

  • Append() is 440 – 25,632 bytes
  • Append() with ObjectPool is 96 to 21,832 bytes

Summary

The next time you need to use the StringBuilder, consider using it from an ObjectPool for a performance gain! There are more performance tips documented in my book Rock Your Code: Code and App Performance for Microsoft .NET which is available on Amazon.com.

If you have any comments, please make them below.


McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!