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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With