CommunityToolkit / CommunityToolkit/dotnet

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

Open
#699 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

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.

```diff
public unsafe string GetOrAdd(ReadOnlySpan span, Encoding encoding)
{
if (span.IsEmpty)
{
return string.Empty;
}

+ if (maxLength <= 128)
+ {
+ Span 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(destination, effectiveLength));
+ }
+ }
+ else
+ {
using SpanOwner buffer = SpanOwner.Allocate(maxLength);

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

return GetOrAdd(new ReadOnlySpan(destination, effectiveLength));
}
+ }
}
```

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.