Skip to content

A high-performance, stack-only string builder that rents its underlying buffer from ArrayPool instead of allocating new arrays. Designed for short-lived string construction.

License

Notifications You must be signed in to change notification settings

soenneker/soenneker.utils.pooledstringbuilders

Soenneker.Utils.PooledStringBuilders

Tiny, fast ref struct string builder. Backed by ArrayPool<char>. Low allocations. Short-lived use.

Install

dotnet add package Soenneker.Utils.PooledStringBuilders

Example

using Soenneker.Utils.PooledStringBuilders;

using var sb = new PooledStringBuilder(128);

sb.Append("Hello, ");
sb.Append(name);
sb.Append(' ');
sb.Append(id);        // ISpanFormattable path, no boxing
sb.AppendLine();

string s = sb.ToString(); // returns string + returns buffer

Cheatsheet

  • new PooledStringBuilder(int capacity = 128)
  • Append(char), Append(string?), Append(ReadOnlySpan<char>)
  • Append<T>(T value, ReadOnlySpan<char> fmt = default, IFormatProvider? prov = null) where T : ISpanFormattable
  • AppendSpan(int length) → write directly into the buffer
  • AppendLine(), AppendSeparatorIfNotEmpty(char)
  • Length, Capacity, Clear()
  • ToString() (keep using; you must Dispose() later)
  • ToStringAndDispose(bool clear = false) (one-shot finish)
  • Dispose() / Dispose(bool clear)

Notes

  • ref struct → stack-only. Don’t capture, box, store in fields, or cross await.
  • Dispose when done. using should be used, or there is ToStringAndDispose(). Don't use both.
  • Handling secrets? Use ToStringAndDispose(clear: true) to zero the array before returning to the pool.
  • Not thread-safe. Keep it short-lived and single-scope.

About

A high-performance, stack-only string builder that rents its underlying buffer from ArrayPool instead of allocating new arrays. Designed for short-lived string construction.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors 2

  •  
  •  

Languages