- Frugal Cafe
- Posts
- FC32 Loads of StringBuilder Extension Methods
FC32 Loads of StringBuilder Extension Methods
Avoiding LOH and temp allocations
In the last episode on StringBuilder cache (FC31: You Need a StringBuilder cache (beehiiv.com)), extension methods are put into StringBuilderExtensions class. We need many more extension methods related to StringBuilder.
Here is the first one I wrote about 9 years ago (recreating from memory):
This extension method is designed to copy the content of StringBuilder piece by piece, and then write to TextWriter; skipping StringBuilder.ToString call which could cause large object allocations. This was added to solve a common problem in .Asp.Net applications, building output pages by layers of StringBuilder/StringWriter. The best approach would be to use a single StringBuilder/StringWriter, but sometimes this is not easy to achieve. So at least, you should try to avoid LOH allocations.
Here is another one:
This pair is designed to avoid LOH allocation inside StringBuilder when a large string is appended to it.
Here is replacement for TextReader.ReadToEnd:
This extension method is designed to reuse both copy buffer and StringBuilder.
This extension method is designed to avoid string generation associated with string.Join when the result is only appended to a StringBuilder:
Here are extension methods for appending integers, no temp string allocation:
Here is for byte data in hex format:
So you really need loads of extension methods for StringBuilder. Source code: FrugalCafe/Common/StringBuilderExtensions.cs at master · ProfFrugal/FrugalCafe (github.com)