• Frugal Cafe
  • Posts
  • FC38: Liberate StringBuilder.AppendFormatHelper

FC38: Liberate StringBuilder.AppendFormatHelper

Making it reusable, opening doors for innovations

String formatting using a pattern string and an argument is a very powerful pattern. In .Net, its implementation goes to StringBuilder.AppendFormatHelper method which only supports sending output to StringBuilder itself.

Let’s liberate it, making it reusable for other similar implementations. First, let’s introduce a new interface for it to send data to:

It turns out, only three methods are needed, to match .Net Framework implementation.

Here is the reusable implementation:

AppendFormat method has a generic argument T with is required to implement ISimpleStringBuilder interface. Its implementation is meant to be struct, so method calls on it can be inlined for performance. This is a powerful trick to achieve abstraction without overhead in C#.

The .Net implementation has an issue which has been bothering me for a while:

This is allocating a StringBuilder for every formatting string. It’s now fixed by renting from StringBuilder cache.

The whole method is quite long. You can read the complete version here: FrugalCafe/Common/StringFormatter.cs at master · ProfFrugal/FrugalCafe (github.com).

Here is a sample implementation of ISimpleStringBuilder

Now let’s write a simple test to check if it really works:

I’m rather excited about such code upcycling because it opens up doors for renovations without repeating code which should be reused.