Skip to content

Buffer<T>.GrowBuffer() allocates with wrong variable, defeating growth strategy #103

@Beldaa

Description

@Beldaa

Severity: High (Performance)

Description

In Buffer<T>.GrowBuffer() (Topten.RichTextKit/Utils/Buffer.cs, line 113), the method calculates an optimal new capacity in the variable newLength (doubling below 1MB, linear 1MB growth above), but then allocates the new array using requiredLength instead of newLength.

This makes the entire growth strategy dead code -- the buffer always allocates exactly the requested size rather than over-allocating for amortized efficiency.

Problematic code

// newLength is calculated correctly above but never used here:
var newData = new T[requiredLength];  // BUG: should be newLength

Impact

  • Performance degradation: Sequential Add() / Insert() / Length setter calls that trigger growth will reallocate on nearly every call instead of amortizing. This turns O(n) bulk insertions into O(n^2).
    • GC pressure: Many more short-lived array allocations since each growth creates an array that's immediately too small for the next insertion.
      • No data corruption: The data is always copied correctly, so results remain correct -- this is purely a performance bug.

Affected components

Buffer<T> is used extensively throughout the library:

  • BiDi algorithm (Bidi.cs, BidiData.cs) -- directionality buffers, resolved levels, isolation mappings
    • Text shaping (TextShaper.cs) -- glyph indices, positions, clusters, codepoint coordinates
      • Utf32Buffer -- extends Buffer<int> for UTF-32 codepoint storage
        • TextDocument (editor)
          Any non-trivial text processing (long paragraphs, BiDi text, complex shaping) would be significantly affected.

Fix

-var newData = new T[requiredLength];
+var newData = new T[newLength];

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions