将一个空的委托吃内存? [英] Will an empty delegate eat up memory?

查看:177
本文介绍了将一个空的委托吃内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在上面的code,我已经初始化 LoggingIn 事件处理程序和一个空的代表。

这会不会影响以任何方式使用的内存空间?尤其是当有上百个事件或数千宣布这样的方式?

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?

推荐答案

刮开previous回答(以下保存为后人)。这取决于编译器的实现,但根据目前的MS C#3.0编译器,这实际上只会造成其重新用于每个实例的单个实例。这是能够做到这一点,因为代表是不可改变的,该委托不需要从实例的任何信息。

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.

我不知道这是否是用C#2.0,虽然如此。你可以反编译你的code,看到了IL是否确实使用缓存的字段或不。用下面的答案是一种安全的方式的保证的你只能创建一个实例,但。

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.

原来的答复:

是的,它创造了一个委托的一个实例。这将需要一些内存。你可以减少,但:

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;
}

在这一点上就只是一个实例,你可以参考它从任何地方。缺点是,其他类可以再取消使用相同的处理。如果你信任你的codeBase类没有做到这一点的休息,这可能是从一个记忆点是最好的选择。

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.

这篇关于将一个空的委托吃内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆