views:

74

answers:

2

Let's say I have a collection of thousands of objects, all of which implement the following:

public event EventHandler StatusChanged = (s,e) => {};
private void ChangeStatus()
{
  StatusChanged(this, new EventArgs());
}

If no handlers are subscribed to that event for each object, does using the no-op event handler provide any performance drawbacks? Or is the CLR smart enough to ignore it? Or am I better off checking for a StatusChanged handler before firing the event?

+1  A: 

Yes, the CLR is not really smart enough to ignore it but the difference should be negligible in most cases.

A method call is not a big deal and is unlikely to have a meaningful impact on the performance of your application.

Mehrdad Afshari
What if I had say 5000 objects potentially firing the event simultaneously? Would that have any noticeable effect?
Marcus
@Marcus: 5000 is not a large number for a 3GHz processor but if you're worried, check for nullity instead of adding an empty handler.
Mehrdad Afshari
@Marcus: Only profiler can answer on that question.
Sergey Teplyakov
A: 

If your application calls ChangeStatus thousand times per second, maybe it would be a problem. But only profiler can prove this.

Sergey Teplyakov
I agree that only a profiler can definitely tell if that's a performance problem. But I always found the practice of adding an empty event handler just to get around a check for null to be a hack. Then again, I write extremely performance-sensitive code, so my point of view might be a bit skewed.
Pepor
@Pepor: Can't agree more. While it's very unlikely to matter performance-wise most of the time, this is just a hack IMO.
Mehrdad Afshari