Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to check if a ReadOnlyMemory<char> contains in a Hashset in C#

I've been looking for some efficient and precise way to check if a ReadOnlyMemory<char> in C# contains in a Hashset of ReadOnlyMemory or any other collection.

I saw some suggestions to convert to string, but I'd highly like to avoid it to enhance memory-efficiency. The only other way that I've found is to write the custom IEqualityComparer, but I'm also wondering if anyone has discovered a better solution.

like image 342
edwp Avatar asked Oct 24 '25 07:10

edwp


1 Answers

You do indeed need a custom comparer. But don't ToString anything inside the comparer, that's inefficient.

Instead use Equals on Spans that you create from the Memory. Also you can use string.GetHashCode which has a Span parameter.

public class ReadOnlyMemoryCharComparer : IEqualityComparer<ReadOnlyMemory<char>>
{
    public static ReadOnlyMemoryCharComparer Instance { get; } = new();

    public bool Equals(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) =>
        x.Span.Equals(y.Span, StringComparison.OrdinalIgnoreCase);

    public int GetHashCode(ReadOnlyMemory<char> obj) =>
        string.GetHashCode(obj.Span, StringComparer.OrdinalIgnoreCase);
}

With the static Instance property, you also don't need to create it every time.

var set = new HashSet<ReadOnlyMemory<char>>(ReadOnlyMemoryCharComparer.Instance);
like image 85
Charlieface Avatar answered Oct 26 '25 22:10

Charlieface