perf: stackalloc single char span, instead of using ToString, for .NET 7

This removes the allocations caused by ToString(). Unfortunately, the ReadOnlySpan<char> overload is only available from .NET 7, and so this is a conditional performance gain. Shame.
This commit is contained in:
Oliver Booth 2023-08-27 01:26:37 +01:00
parent cfe70a7923
commit bd823ba818
Signed by: oliverbooth
GPG Key ID: B89D139977693FED
2 changed files with 8 additions and 1 deletions

View File

@ -38,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
BigEndian/LittleEndian methods.
- X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` now throw ArgumentException in lieu of
TypeInitializationException.
- X10D: `char.IsEmoji` no longer allocates for .NET 7.
### Removed

View File

@ -18,7 +18,13 @@ public static class CharExtensions
[MethodImpl(CompilerResources.MethodImplOptions)]
public static bool IsEmoji(this char value)
{
return value.ToString().IsEmoji();
#if NET7_0_OR_GREATER
Span<char> chars = stackalloc char[1];
chars[0] = value;
return EmojiRegex.Value.IsMatch(chars);
#else
return EmojiRegex.Value.IsMatch(value.ToString());
#endif
}
/// <summary>