Considering the following basic event-related code inside a class:
public event EventHandler Updated;
public void OnUpdated() {
if (Updated != null) Updated(sender: this, e: null)
}
If no one has subscribed to the Updated event, I would not like the fourth line to cause any significant performance drag (the idea is to let subscribers choose the most fine-grained events to subscribe to have only the minimal number of events fired and prevent a message queue overload).
Should I care and track the existence of subscribers (e.g. with if (Updated != null && OnUpdateSubscribed) Updated(sender: this, e: null) or trust the compiler/runtime?
The check
OnUpdate != nulldefines an event being subscribed / unsubscribed. In fact, there is no real difference between a boolean check and a null check, because ultimately both of them are just a “load field”, “branch if false” – because a null reference counts as “false” as far as logic checks are concerned.My only suggestion would be: store it in a local variable, to prevent a (pretty unlikely, but possible) race condition:
So: no, basically: there is no overhead of this.
Example:
Compiles to (comments are mine):