A fast and low allocation StringBuilder for .NET.
Install the package:
PM> Install-Package LinkDotNet.StringBuilder
Afterwards use the package as follow:
ValueStringBuilder stringBuilder = new ValueStringBuilder();
stringBuilder.AppendLine("Hello World");
string result = stringBuilder.ToString();
The dotnet version of the StringBuilder
is a all purpose version which normally fits a wide variety of needs.
But sometimes low allocation is key. Therefore I created the ValueStringBuilder
. It is not a class but a ref struct
which tries to do as less allocations as possible.
If you want to know how the ValueStringBuilder
works and why it uses allocations and is even faster, checkout this blog post.
The blog goes a bit more in detail how it works with a simplistic version of the ValueStringBuilder
.
The library is not meant as a general replacement for the StringBuilder
shipped with the .net framework itself. You can head over to the documentation and read about the "Known limitations".
The library works best for a small to medium amount of strings (not multiple 100'000 characters, even though it is still faster and uses less allocations). At anytime you can convert the ValueStringBuilder
to a "normal" StringBuilder
.
A more detailed documentation can be found here.
The following table gives you a small comparison between the StringBuilder
which is part of .NET and the ValueStringBuilder
:
| Method | Mean | Error | StdDev | Gen 0 | Allocated |
| ------------------- | -------: | ------: | ------: | -----: | --------: |
| DotNetStringBuilder | 430.7 ns | 8.52 ns | 7.55 ns | 0.3576 | 1,496 B |
| ValueStringBuilder | 226.7 ns | 2.45 ns | 2.05 ns | 0.1395 | 584 B |
Checkout the Benchmark for more detailed comparison and setup.