When using LINQ extension methods like Enumerable.Select, is it better to use a Lambda expression, or a regular method?
I’m asking this both with respect to (memory) optimization*, and to readability**.
Example code:
private void Main() {
var array = new int[1];
var result1 = array.Select(x => x.ToString()); // Lambda
var result2 = array.Select(LinqHelper); // method
}
private string LinqHelper(int x) {
return x.ToString();
}
*I’m mostly thinking of closures creating scopes with unused instantiated variables in them, simply because those variables were in scope when the Lambda was created. Edit – this was stupid thinking, since variables are only captured by a closure when they’re referenced in the Lambda expression.
**Both options look OK to me.
From an optimization point of view, there should be no difference.
From a readability point of view, I’d think about whether you need the same logic in several places. If so, use a method and use a method group conversion. That way you don’t repeat yourself, so you don’t have to change several bits of code if your requirements change.
If you’re only using the logic in a single place and it’s short, a lambda expression captures the logic “inline” in a way which is usually easier to read IMO.
I typically avoid long lambda expressions, with the possible exception of use with TPL, e.g.