C
C#2y ago
Thinker

Lambda or extension method reference [Answered]

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?
7 Replies
Becquerel
Becquerel2y ago
I believe there is a very minor performance gain by using the method group over the explicit lambda however, you shouldn't care about performance until you have a reason to and have identified bottlenecks I personally think using the method group looks much nicer, so that's what I use when I can
Thinker
Thinker2y ago
I kind of think the opposite, but good to know Having to write the name of an extension class feels... weird
Becquerel
Becquerel2y ago
i agree - this might be one of the places where i make an exception it's ultimately up to your preference, in any situation where the performance mattered it would be outshined by using LINQ to begin with
Thinker
Thinker2y ago
Fair
333fred
333fred2y ago
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 This is yet another example of trying to optimize based on an implementation detail In both of these cases, you need an instance of a Func<T1, T2> One creates a lambda, the other uses a method group. In either case, you need to allocate memory
Thinker
Thinker2y ago
Fair point
Accord
Accord2y ago
✅ This post has been marked as answered!