Skip to content

Perf: stackalloc on short inputs to StringPool.GetOrAdd(ReadOnlySpan<byte>, Encoding) #699

Open

Description

@ovska

Currently for all non-empty inputs an array is rented from the pool. My naive assumption is, however, that the pool is commonly used for shorter strings. I suggest stackalloc be used when GetMaxCharCount is small, e.g. 64 or 128.

public unsafe string GetOrAdd(ReadOnlySpan<byte> span, Encoding encoding)
{
    if (span.IsEmpty)
    {
        return string.Empty;
    }

+   if (maxLength <= 128)
+   {
+       Span<char> buffer = stackalloc char[maxLength];

+       fixed (byte* source = span)
+       fixed (char* destination = &buffer.DangerousGetReference())
+       {
+           int effectiveLength = encoding.GetChars(source, span.Length, destination, maxLength);
+
+           return GetOrAdd(new ReadOnlySpan<char>(destination, effectiveLength));
+       }
+   }
+   else
+   {
        using SpanOwner<char> buffer = SpanOwner<char>.Allocate(maxLength);

        fixed (byte* source = span)
        fixed (char* destination = &buffer.DangerousGetReference())
        {
            int effectiveLength = encoding.GetChars(source, span.Length, destination, maxLength);

            return GetOrAdd(new ReadOnlySpan<char>(destination, effectiveLength));
        }
+   }
} 

Issue submitted without a template as this isn't an API request or a bug report.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions