Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 730
RainCast Avatar asked Dec 30 '14 10:12

RainCast


1 Answers

I don't think this matters a lot, both in assumed performance gain and actual difference.

Both GetInvocationList and -= walk the internal array _invocationList. (See source)

The LINQ extension method Contains will take more time since it needs the entire array to be walked and converted, returned and then checked by Contains itself. The Contains has the advantage it doesn't need to add the event handler if it exists which will mean some performance gain.

like image 185
Patrick Hofman Avatar answered Oct 22 '22 03:10

Patrick Hofman