Will an empty delegate eat up memory?

2019-02-21 14:49发布

问题:

public sealed class FtpManager
{
    public event EventHandler LoggingIn = delegate { };
    private void OnLoggingIn(object sender, EventArgs e)
    {
        var handler = LoggingIn;
        handler(sender, e);
    }
// ...
}

In the above code, I have initialized LoggingIn event handler with an empty delegate.

Will that affect memory space used in any way? Especially when there are hundreds or thousands of events declared such way?

回答1:

Scratch the previous answer (kept below for posterity). It depends on the implementation of the compiler, but under the current MS C# 3.0 compiler, this actually only creates a single instance which is reused for every instance. It's able to do that because delegates are immutable and that delegate doesn't require any information from the instance.

I don't know whether this was the case with C# 2.0 though. You can decompile your code and see whether the IL actually uses a cached field or not. Using the answer below is a safe way to guarantee you'll only create one instance though.

Original answer:

Yes, it creates an instance of a delegate. That will take some memory. You could reduce that though:

public static class EventHandlers
{
    public static readonly EventHandler Empty = delegate {};
}

public sealed class FtpManager
{
    public event EventHandler LoggingIn = EventHandlers.Empty;
}

At that point there'll just be the one instance, and you can refer to it from anywhere. The downside is that other classes could then unsubscribe using the same handler. If you trust the rest of your codebase not to do that, this is probably the best bet from a memory point of view.



回答2:

The alternative to doing this is checking LoggingIn for nullity every time you want to raise it. That's liable to be more memory intensive than calling an empty delegate.