RainCast RainCast - 2 months ago 16
C# Question

Which C# pattern has better performance to avoid duplicated event handlers?

There are basically two patterns in avoiding duplicated registering of event handlers:
(According to this discussion: C# pattern to prevent an event handler hooked twice)


  1. Using System.Linq namespace, and check if the event handler is registered by calling
    GetInvocationList().Contains(MyEventHandlerMethod);

  2. Do the unregistering before registering, like this:

    MyEvent -= MyEventHandlerMethod;
    MyEvent += MyEventHandlerMethod;



My question is, performance-wise, which one is better, or is there a significant difference between them in performance?

Answer

According the documentation, invocation list is being stored as array or something similar to it, and the order of the event handlers is being stored too. May be there are inner structure to maintain fast search for a particular method there.

So in the worst case operation of the GetInvocationList().Contains(MyEventHandlerMethod); is O(1) (as we simply got the reference for the array) + O(n) for searching the method, even if there is no optimization for it. I seriously doubt that this is true, and I think that there is some optimizing code, and it is O(log_n).

Second approach has additional operation of adding which is, I think, O(1), as we adding the event handler to the end.

So, to see the difference between such actions, you need a lot of the event handlers.
But! If you use the second approach, as I said, you'll add the event handler to the end of the queue, which can be wrong in some cases. So use the first one, and has no doubt in it.