Empty EventArgs

There is a small performance improvement you can make when invoking an event with new EventArgs. Usually, you have a code similar to this.

public event EventHandler<EventArgs> Clicked;

protected virtual void OnClicked()
{
    EventHandler<EventArgs> temp = Clicked;
    if (temp != null) temp(this, new EventArgs());
}

By the way, this invocation isn’t a 100% thread-safe and it might be theoretically JITted (but it won’t because it would cause lots of breaking changes since Microsoft originally promoted this pattern).

But back to the original idea, there is a static property EventArgs.Empty and you should use instead of the new object allocation. After that, the improved code looks like this.

public event EventHandler<EventArgs> Clicked;

protected virtual void OnClicked()
{
    EventHandler<EventArgs> temp = Clicked;
    if (temp != null) temp(this, EventArgs.Empty);
}

You won’t get a massive improvement, but something is better than nothing and also I find this code easier to read.


Did you like the article? Send me a comment!