代表,行动和内存分配 [英] Delegates, Actions and Memory Allocations

查看:68
本文介绍了代表,行动和内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理需要最少内存分配的代码块。

I'm currently working on a chunk of code that requires minimum memory allocations.

我注意到,如果我对参数使用方法,则编译器会更改代码并创建一个 Action ,但是如果我使用匿名方法,则编译器会创建一个委托块。我知道新的 Action 会分配内存,但是我不确定委托。

I've noticed if I use a method for a parameter the compiler changes the code and creates a new Action, but if I use an anonymous method the compiler creates a delegate block. I'm aware that the new Action allocates memory, but I'm not so sure about the delegate. Will delegates allocate memory when used?

我的代码:

bool workfinished = false;

void DoWork()
{
    MyMethod(CallBack1Work, ()=>{ workfinished = false;});
}

void MyMethod(Action callback1, Action callback2)
{
}

void CallBack1Work()
{
}

编译器版本:

bool workfinished = false;

void DoWork()
{
    MyMethod(new Action( CallBack1Work ), delegate{ workfinished = false;});
}

void MyMethod(Action callback1, Action callback2)
{
}

void CallBack1Work()
{
}
        
void DoWork_b01()
{
    workfinished = false;
}


推荐答案

您明确使用 new SomeDelegate 或忽略它,无论您使用lambda, delegate 关键字还是传递方法组或您未显示的任何可能的解决方案。在每种情况下,都会创建一个委托对象。编译器经常可以推断出它应该在那儿,因此不会强迫您键入它;但是无论如何,该代表的创建仍在进行。 (从技术上讲,您可以传入 null 而不分配对象,但是您永远无法做任何工作,因此我认为忽略这种情况是安全的。)

It doesn't matter whether you explicit use new SomeDelegate or omit it, whether you use a lambda, the delegate keyword, or pass in a method group, or any possible solution you haven't shown. In every single case a delegate object will be created. The compiler can often infer that it should be there, so it doesn't force you to type it out; but the creation of that delegate is still happening no matter what. (Well, technically you could pass in null and not allocate an object, but then you can't ever do any work, so I think it's safe to ignore that case.)

每个选项之间的内存分配的唯一真正区别是,在给定的匿名方法块中,您正在关闭变量( workfinished )。为了创建该闭包,运行时将生成其自己的类型来存储闭包的状态,创建该类型的实例,并将其用于委托,因此所有使用匿名方法的解决方案都将创建一个新对象。 (当然,它很小,因此在大多数情况下它不会变得特别昂贵。)

The only real difference in memory allocations between each of the options is that in the given anonymous method blocks you are closing over a variable (workfinished). In order to create that closure the runtime will generate it's own type to store the state of the closure, create an instance of that type, and use that for the delegate, so all of the solutions using an anonymous method are creating one new object. (Granted, it's small, so it's not going to be particularly expensive in most situations.)

这篇关于代表,行动和内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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