Does using a lambda expression generate garbage for the GC opposed to the normal foreach loop?
// Lambda version
Foos.ForEach(f=>f.Update(gameTime));
// Norm
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 Foos, DateTime gameTime)
{
Foos.ForEach(f => f.Update(gameTime));
}
Will get translated to this:
private static void TestLambda(List Foos, DateTime gameTime)
{
Program.<>c__DisplayClass1 <>c__DisplayClass = new Program.<>c__DisplayClass1();
<>c__DisplayClass.gameTime = gameTime;
Foos.ForEach(new Action(<>c__DisplayClass.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).