C
Join ServerC#
help
Lambda or extension method reference [Answered]
Tthinker2278/30/2022
If you have an extension which maps a type A to another type B and you have an enumerable of type A which you want to turn into an enumerable of type B, should you prefer
.Select(x => x.ToB())
or .Select(Extensions.ToB)
? The first I assume allocates an extra unnecessary lambda which the second doesn't?BBecquerel8/30/2022
I believe there is a very minor performance gain by using the method group over the explicit lambda
BBecquerel8/30/2022
however, you shouldn't care about performance until you have a reason to and have identified bottlenecks
BBecquerel8/30/2022
I personally think using the method group looks much nicer, so that's what I use when I can
Tthinker2278/30/2022
I kind of think the opposite, but good to know
Tthinker2278/30/2022
Having to write the name of an extension class feels... weird
BBecquerel8/30/2022
i agree - this might be one of the places where i make an exception
BBecquerel8/30/2022
it's ultimately up to your preference, in any situation where the performance mattered it would be outshined by using LINQ to begin with
Tthinker2278/30/2022
Fair
OOrannis8/30/2022
The first I assume allocates an extra unnecessary lambda which the second doesn't?No. In fact, up until recently, the first would be more memory-friendly
OOrannis8/30/2022
This is yet another example of trying to optimize based on an implementation detail
OOrannis8/30/2022
In both of these cases, you need an instance of a
Func<T1, T2>
OOrannis8/30/2022
One creates a lambda, the other uses a method group. In either case, you need to allocate memory
Tthinker2278/30/2022
Fair point
AAccord8/30/2022
✅ This post has been marked as answered!