linkdotnet / StringBuilder

A fast and low allocation StringBuilder for .NET.

Home Page:https://linkdotnet.github.io/StringBuilder

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use rope-like structure with `ref` fields

linkdotnet opened this issue · comments

In the current setup the ValueStringBuilder has one large array internally. Where this is fine for most cases, it can get tricky for either very big buffers (>85kb) or if we have to grow the buffer a lot.

A different approach would be to use a rope-like structure with a fixed size (kind of like the real StringBuilder that has always chunks of 8000 characters).

In contrast to System.Text.StringBuilder, one could try to create always new ropes when appending. So our ValueStringBuilder would be structured like a linked list. When appending a string we add another instance of ValueStringBuilder to the current one.

The internal structure could look like this:

public ref struct ValueStringBuilder
{
    public ref ValueStringBuilder next;

    public void Append(ReadOnlySpan<char> string)
    {
        ref var nextInstance = next;
        while(!Unsafe.IsNullRef(nextInstance.next)) { nextInstance = nextInstance.next; }

        nextInstance.next = new ValueStringBuilder(string);
    }
}

Currently this is not allowed with C# 11.