From bd823ba8182b3409048c98d3e394ac913a853027 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 27 Aug 2023 01:26:37 +0100 Subject: [PATCH] perf: stackalloc single char span, instead of using ToString, for .NET 7 This removes the allocations caused by ToString(). Unfortunately, the ReadOnlySpan overload is only available from .NET 7, and so this is a conditional performance gain. Shame. --- CHANGELOG.md | 1 + X10D/src/Text/CharExtensions.cs | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f31c88..77ec199 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/X10D/src/Text/CharExtensions.cs b/X10D/src/Text/CharExtensions.cs index 2a3eef8..06ca0f7 100644 --- a/X10D/src/Text/CharExtensions.cs +++ b/X10D/src/Text/CharExtensions.cs @@ -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 chars = stackalloc char[1]; + chars[0] = value; + return EmojiRegex.Value.IsMatch(chars); +#else + return EmojiRegex.Value.IsMatch(value.ToString()); +#endif } ///