How much performance overhead is there in using events?

Viewed 16320

I am fairly new to programming and with my limited knowledge of OOP have decided to use events to communicate between my classes. Naturally, this will lead to quite a few events.

I wanted to know if there is any additional overhead to using events? I would assume that unless an event is acted upon (i.e, there is a listener in a class that executes a function based on the event being fired), then there shouldn't really be much of an impact. But I am not intimately familiar with events in C# and wanted to just confirm if there is significant extra overhead simply for firing off an event?

5 Answers

In case anyone stumbles upon this question so many years after, I've used the BenchMarkDotNet framework to measure the time an event takes to invoke. I've made a difference between 1 subscriber and 100 subscribers.

Test code used:

private event EventHandler TestEventSingle;
private event EventHandler TestEventMultiple;

public OtherTests()
{
    TestEventSingle += OtherTests_TestEvent;

    for (int i = 0; i < 100; i++)
    {
        TestEventMultiple += OtherTests_TestEventMultiple;
    }
}

private void OtherTests_TestEventMultiple(object sender, EventArgs e)
{
    //Do something with the event...
}

private void OtherTests_TestEvent(object sender, EventArgs e)
{
    //Do something with the event...
}

[Benchmark]
public void InvokeEvent()
{
    TestEventSingle.Invoke(this, null);
}
[Benchmark]
public void InvokeEventMore()
{
    TestEventMultiple.Invoke(this, null);
}
[Benchmark]
public void CallMethod()
{
    OtherTests_TestEvent(this, null);
}
[Benchmark]
public void CallMethodMore()
{
    for (int i = 0; i < 100; i++)
    {
        OtherTests_TestEventMultiple(this, null);
    }
}

Test results:

Method Mean Error StdDev
InvokeEvent 1.6774 ns 0.0246 ns 0.0230 ns
InvokeEventMore 192.2076 ns 3.6115 ns 3.3782 ns
CallMethod 0.0317 ns 0.0106 ns 0.0099 ns
CallMethodMore 37.1203 ns 0.4147 ns 0.3676 ns
Related