0

I need to implement the IEqualityComparer<Delegate> interface to define an implementation of GetHashCode() for delegates. This is needed because I wish to have a dictionary with delegates as keys, and the default implementation of GetHashCode() for delegates is simply ->

public override int GetHashCode()
{
    return base.GetType().GetHashCode();
}

As noted here - Why do 2 delegate instances return the same hashcode? - the above, default implementation will make using delegates in a dictionary as slow as a list (O(n) for lookups).

So I am considering my own implementation which uses System.Reflection.MethodInfo like so ->

public int GetHashCode(Delegate? obj)
{
    if (obj == null)
        return 0;
    else
        return obj.Method.GetHashCode();
}

But given that MethodInfo's GetHashode() method is contained in the system.reflection namespace, will the above implementation be very slow? I know that reflection can be costly, and since the GetHashCode() method will be used by the dictionary it is important that invocations are not slow.

Treker
  • 386
  • 2
  • 9
  • 1
    If the `MethodInfo` object that that `Method` property refers to already exists, which it presumably would, then there's no overhead with getting that `MethodInfo`. You can look at the source code for that `GetHashCode` method yourself to see what it does to see whether there's any overhead involved there, but I doubt there is. – John Sep 21 '22 at 07:58
  • 3
    The idea that anything and everything to do with reflection is slow is a misconception. Many reflection operations are proactively cached by the runtime or just involve reading off fields that are part of the object definition anyway. But, more importantly, if you want to know if something is *unacceptably* slow, time it. This is why things like BenchmarkDotNet exist. Better yet, profile your actual code in context, lest you focus on optimizing the wrong thing. – Jeroen Mostert Sep 21 '22 at 08:20

0 Answers0