Skip to content

nuskey8/SmolStr

Repository files navigation

SmolStr

Small-string optimized string type for .NET

NuGet Releases license

Installation

SmolStr requires .NET Standard 8 or higher. Packages are available on NuGet.

$ dotnet package add SmolStr

Usage

using SmolStr;

SmallString str1 = "hello!";
Console.WriteLine(str1.AsSpan());

SmallString str2 = SmallString.Create($"hello {DateTime.Now.Year}");
Console.WriteLine(str2.AsSpan()); // hello 2026

Design

SmallString, like System.String, handles UTF-16 encoded strings, but is optimized for smaller strings. SmallString is a struct that stores strings up to SmallString.MaxInlineSize = 16 characters on the stack, and longer strings on the heap.

SmallString has a size of 40 bytes and its general structure is as follows:

unsafe struct SmallString
{
    object? obj;
    fixed char data[MaxInlineLength];
}

Due to .NET runtime limitations, managed references and other values ​​cannot be overlapped in [FieldOffset]. Therefore, the size of the obj field cannot be removed. Instead, a boxed byte object representing the length of small strings is placed here.

License

This library is under the MIT License.

About

Small-string optimized string type for .NET

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages