views:

94

answers:

2

I have a problem which I could solve using something like this

sortedElements.ForEach((XElement el) => PrintXElementName(el,i++));

And this means that I have in ForEach a lambda which permits using parameters like int i.

I like that way of doing it, but i read somewhere that anonymous methods and delegates with lambda leads to a lot of memory leaks because each time when lambda is executed something is instantiated but is not released. Something like that.

Could you please tell me if this is true in this situation and if it is why?

+6  A: 

I like that way of doing it, but i read somewhere that anonymous methods and delegates with lambda leads to a lot of memory leaks because each time when lambda is executed something is instantiated but is not released

No, that is not true. Now the used resources won't be released until the delegate is garbage collected. It's just like any other managed object, but using a Lambda expression in most cases is not any less efficient than accomplishing the same thing another way.

This isn't to say that you couldn't make a lamda expression cause a massive memory leak, it's just like any other code. If you were to say do something like

(x => //open unmanaged resource here and not close it....)

and call that in a foreach loop, that could be really bad.

What you have to remember is that your Lamda expression is essentially

(XElement el) => PrintXElementName(el,i++)

void Your_Function (XElement el)
{
    PrintXElementName(el,i++);
}
Kevin
Shoudlnt' it be `return PrintXElementName(el,i++);`?
Bastien Léonard
ForEach doesn't return anything. It loops through each element in the collection.
Kevin
A: 

It's not worth worrying about until you profile your application and it does leak memory.

DeadMG