C# Does Lambda => generate garbage?

雨燕双飞 提交于 2019-12-02 20:24:26

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

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

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).

In this case I think that you are using a generic method (ForEach) which will generate a new type (assuming that Foo is a reference type, only one new type will be generated), and the lambda will be compiled as a regular anonymous method. Nothing about that suggests any sort of linear increase in memory usage.

As far as the profiler is concerned, you are not measuring anything about memory or the GC. You are measuring time spent executing the method, and the lambda should not be significantly slower than the 'regular' way.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!