C#请问波长=>产生的垃圾? [英] C# Does Lambda => generate garbage?

查看:115
本文介绍了C#请问波长=>产生的垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用是否lambda表达式生成不是正常的foreach循环的GC?

Does using a lambda expression generate garbage for the GC opposed to the normal foreach loop?

// Lambda version
Foos.ForEach(f=>f.Update(gameTime));

// Normal approach:
foreach (Foo f in Foos)
{
  f.Update(gameTime);
}



在CLR探查表明,我有69.9%system.Action< T>我怀疑是foreach循环的兰巴版本之上。真的是这样

The CLR profiler shows that I have 69.9% system.Action< T > and I suspect that being the lamba version of the foreach loop as above. Is that true?

编辑:?我用了微软CLR分析器:的http://download.microsoft.com/download/4/4/2/442d67c7-a1c1-4884-9715-803a7b485b82/clr%20profiler。 exe文件
http://msdn.microsoft.com/en-us/库/ ff650691.aspx

I used the Microsoft CLR profiler: http://download.microsoft.com/download/4/4/2/442d67c7-a1c1-4884-9715-803a7b485b82/clr%20profiler.exe or http://msdn.microsoft.com/en-us/library/ff650691.aspx

推荐答案

是的,一个lambda如果关闭从本地捕获的变量将建立垃圾范围(即 gameTime 在这种情况下)。

Yes, a lambda will create garbage if the closure captures a variable from the local scope (i.e. gameTime in this context).

例如,下面的C#功能:

For example, the following C# function:

static void TestLambda(List<Foo> Foos, DateTime gameTime)
{
    Foos.ForEach(f => f.Update(gameTime));
}



将得到翻译成这样的:

Will get translated to this:

private static void TestLambda(List<Foo> Foos, DateTime gameTime)
{
    Program.<>c__DisplayClass1 <>c__DisplayClass = new Program.<>c__DisplayClass1();
    <>c__DisplayClass.gameTime = gameTime;
    Foos.ForEach(new Action<Foo>(<>c__DisplayClass.<TestLambda>b__0));
}

请注意,有的两个<$的的实例C $ C>新在生成的代码,这意味着不仅有动作对象被分配(封锁),但也反对举行捕获的变量(可变逃逸记录)。

Note that there are two instances of new in the resulting code, meaning that there is not only Action objects being allocated (the closures), but also objects to hold the captured variables (escaping variable records).

这篇关于C#请问波长=&GT;产生的垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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