Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribing from events - performance hit?

Consider the following code (from a performance report):

Performance report

This is part of a property notificiation listener component. The method OnItemPropertyChanged is a private instance-bound method with the PropertyChangedEventHandler signature. This method is called around 100.000 times and is causing significant delays in the application.

Are there performance considerations related to (un)subscribing events? Is there an explanation to why this would cause such a performance hit?

like image 215
Bas Avatar asked Jun 16 '14 07:06

Bas


1 Answers

The first thing to note is that:

notificationItem.PropertyChanged -= OnItemPropertyChanged;

actually allocated a new delegate for the purpose. It also means that the equivalence test can't short-circuit at identity equivalence - it has to perform method/target equivalence (i.e. a different delegate instance, but same target/method, hence considered equivalent for the purposes of delegate combination).

What I would try first would be using a single delegate instance, i.e.

void OnItemPropertyChanged(object sender, PropertyChangedEventArgs args) {...}

private readonly PropertyChangedEventHandler sharedHandler;
public YourType() { // constructor
    sharedHandler = OnItemPropertyChanged;
}

Then when you subscribe, instead of:

notificationItem.PropertyChanged += OnItemPropertyChanged;

or

notificationItem.PropertyChanged -= OnItemPropertyChanged;

use instead:

notificationItem.PropertyChanged += sharedHandler;

or

notificationItem.PropertyChanged -= sharedHandler;

Worth a try, at least.

like image 118
Marc Gravell Avatar answered Sep 18 '22 12:09

Marc Gravell