Consider the following code (from a 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?
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.
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