When not to use lambda expressions [closed]
Asked Answered
M

9

56

A lot of questions are being answered on Stack Overflow, with members specifying how to solve these real world/time problems using lambda expressions.

Are we overusing it, and are we considering the performance impact of using lambda expressions?

I found a few articles that explores the performance impact of lambda vs anonymous delegates vs for/foreach loops with different results

  1. Anonymous Delegates vs Lambda Expressions vs Function Calls Performance
  2. Performance of foreach vs. List.ForEach
  3. .NET/C# Loop Performance Test (FOR, FOREACH, LINQ, & Lambda).
  4. DataTable.Select is faster than LINQ

What should be the evaluation criteria when choosing the appropriate solution? Except for the obvious reason that it's more concise code and readable when using lambda.

Meghannmegiddo answered 23/3, 2009 at 10:49 Comment(0)
F
36

Even though I will focus on point one, I begin by giving my 2 cents on the whole issue of performance. Unless differences are big or usage is intensive, usually I don't bother about microseconds that when added don't amount to any visible difference to the user. I emphasize that I only don't care when considering non-intensive called methods. Where I do have special performance considerations is on the way I design the application itself. I care about caching, about the use of threads, about clever ways to call methods (whether to make several calls or to try to make only one call), whether to pool connections or not, etc., etc. In fact I usually don't focus on raw performance, but on scalibility. I don't care if it runs better by a tiny slice of a nanosecond for a single user, but I care a lot to have the ability to load the system with big amounts of simultaneous users without noticing the impact.

Having said that, here goes my opinion about point 1. I love anonymous methods. They give me great flexibility and code elegance. The other great feature about anonymous methods is that they allow me to directly use local variables from the container method (from a C# perspective, not from an IL perspective, of course). They spare me loads of code oftentimes. When do I use anonymous methods? Evey single time the piece of code I need isn't needed elsewhere. If it is used in two different places, I don't like copy-paste as a reuse technique, so I'll use a plain ol' delegate. So, just like shoosh answered, it isn't good to have code duplication. In theory there are no performance differences as anonyms are C# tricks, not IL stuff.

Most of what I think about anonymous methods applies to lambda expressions, as the latter can be used as a compact syntax to represent anonymous methods. Let's assume the following method:

public static void DoSomethingMethod(string[] names, Func<string, bool> myExpression)
{
    Console.WriteLine("Lambda used to represent an anonymous method");
    foreach (var item in names)
    {
        if (myExpression(item))
            Console.WriteLine("Found {0}", item);
    }
}

It receives an array of strings and for each one of them, it will call the method passed to it. If that method returns true, it will say "Found...". You can call this method the following way:

string[] names = {"Alice", "Bob", "Charles"};
DoSomethingMethod(names, delegate(string p) { return p == "Alice"; });

But, you can also call it the following way:

DoSomethingMethod(names, p => p == "Alice");

There is no difference in IL between the both, being that the one using the Lambda expression is much more readable. Once again, there is no performance impact as these are all C# compiler tricks (not JIT compiler tricks). Just as I didn't feel we are overusing anonymous methods, I don't feel we are overusing Lambda expressions to represent anonymous methods. Of course, the same logic applies to repeated code: Don't do lambdas, use regular delegates. There are other restrictions leading you back to anonymous methods or plain delegates, like out or ref argument passing.

The other nice things about Lambda expressions is that the exact same syntax doesn't need to represent an anonymous method. Lambda expressions can also represent... you guessed, expressions. Take the following example:

public static void DoSomethingExpression(string[] names, System.Linq.Expressions.Expression<Func<string, bool>> myExpression)
{
    Console.WriteLine("Lambda used to represent an expression");
    BinaryExpression bExpr = myExpression.Body as BinaryExpression;
    if (bExpr == null)
        return;
    Console.WriteLine("It is a binary expression");
    Console.WriteLine("The node type is {0}", bExpr.NodeType.ToString());
    Console.WriteLine("The left side is {0}", bExpr.Left.NodeType.ToString());
    Console.WriteLine("The right side is {0}", bExpr.Right.NodeType.ToString());
    if (bExpr.Right.NodeType == ExpressionType.Constant)
    {
        ConstantExpression right = (ConstantExpression)bExpr.Right;
        Console.WriteLine("The value of the right side is {0}", right.Value.ToString());
    }
 }

Notice the slightly different signature. The second parameter receives an expression and not a delegate. The way to call this method would be:

DoSomethingExpression(names, p => p == "Alice");

Which is exactly the same as the call we made when creating an anonymous method with a lambda. The difference here is that we are not creating an anonymous method, but creating an expression tree. It is due to these expression trees that we can then translate lambda expressions to SQL, which is what Linq 2 SQL does, for instance, instead of executing stuff in the engine for each clause like the Where, the Select, etc. The nice thing is that the calling syntax is the same whether you're creating an anonymous method or sending an expression.

Fastigiate answered 23/3, 2009 at 12:27 Comment(0)
E
29

My answer will not be popular.

I believe Lambda's are 99% always the better choice for three reasons.

First, there is ABSOLUTELY nothing wrong with assuming your developers are smart. Other answers have an underlying premise that every developer but you is stupid. Not so.

Second, Lamdas (et al) are a modern syntax - and tomorrow they will be more commonplace than they already are today. Your project's code should flow from current and emerging conventions.

Third, writing code "the old fashioned way" might seem easier to you, but it's not easier to the compiler. This is important, legacy approaches have little opportunity to be improved as the compiler is rev'ed. Lambdas (et al) which rely on the compiler to expand them can benefit as the compiler deals with them better over time.

To sum up:

  1. Developers can handle it
  2. Everyone is doing it
  3. There's future potential

Again, I know this will not be a popular answer. And believe me "Simple is Best" is my mantra, too. Maintenance is an important aspect to any source. I get it. But I think we are overshadowing reality with some cliché rules of thumb.

// Jerry

Eclipse answered 20/12, 2011 at 22:27 Comment(4)
The only thing wrong with this answer is the mistake in the first sentence :)Humism
I can't believe I didn't mention that reducing the lines of code increases the readability of your source. I can absorb 2,700 lines far easier than 27,000. Lambdas help reduce lines of code.Eclipse
This answer has two problems, one you're not answering the question, the question is about that 1%. Two, you straight away start with "better", but better than what? If you meant compared to delegate keyword, I agree. If you meant better than writing named methods, then I disagreeDang
So basically, everyone else is doing it, and who cares if your code isn't readable. Got it.Goglet
D
19

Code duplication.
If you find yourself writing the same anonymous function more than once, it shouldn't be one.

Discordancy answered 23/3, 2009 at 10:56 Comment(5)
It depends where the code is being duplicated. Say you have to sort a list using the same condition a few times within a method. I'd probably declare a lambda in the method scope and reuse that. But overall, I'd agree with this! +1Factory
Well, not quite. If your types are even remotely complex, specifying the full type of the lambda might be considerably more work than duplicating it a few times.Oceanus
That's what 'var' is for. OTOH, if you need to pass or return the lambda as a parameter, then I agree.Katharinakatharine
I don't know if that's strictly correct, though. What about complexity? I don't think there's any problem with writing "p => p + 1" or the like multiple times; it seems like it would be more of a schlep to extract it.Ichnography
This is the correct answer. The accepted answer is full of cliches and opinions.Fife
T
14

Well, when we are talking bout delegate usage, there shouldn't be any difference between lambda and anonymous methods -- they are the same, just with different syntax. And named methods (used as delegates) are also identical from the runtime's viewpoint. The difference, then, is between using delegates, vs. inline code - i.e.

list.ForEach(s=>s.Foo());
// vs.
foreach(var s in list) { s.Foo(); }

(where I would expect the latter to be quicker)

And equally, if you are talking about anything other than in-memory objects, lambdas are one of your most powerful tools in terms of maintaining type checking (rather than parsing strings all the time).

Certainly, there are cases when a simple foreach with code will be faster than the LINQ version, as there will be fewer invokes to do, and invokes cost a small but measurable time. However, in many cases, the code is simply not the bottleneck, and the simpler code (especially for grouping, etc) is worth a lot more than a few nanoseconds.

Note also that in .NET 4.0 there are additional Expression nodes for things like loops, commas, etc. The language doesn't support them, but the runtime does. I mention this only for completeness: I'm certainly not saying you should use manual Expression construction where foreach would do!

Topic answered 23/3, 2009 at 11:13 Comment(8)
SLightly off topic, but I mean to have heard something on the lines of the List.ForEach(. => .. ) to be faster/more efficient/or something than using foreach( .. ) { .. } because it has access to the internal array and doesnt use enumerators and such? may be wrong though...Charla
It may well have such access, but it needs to do delegate invoke, so double edged. You would need to profile to be sure, but I would expect foreach to be marginally quicker.Topic
Ironically, that's not the case. Believe it or nor, List.ForEach has the edge. Invocation of a single delegate is quite fast (approaching the same speed as an interface call).Rebeccarebecka
@Dustin - is that comparing against List<T>.Enumerator, or IEnumerator<T>?Topic
@marc-gravell: "foreach" will compile using List<T>.Enumerator and List<T>.ForEach is still faster. See: diditwith.net/2006/10/05/… msmvps.com/blogs/jon_skeet/archive/2006/01/20/foreachperf.aspxRebeccarebecka
Bear in mind that "foreach" essentially calls two methods on each iteration while List<T>.ForEach performs one delegate invocation.Rebeccarebecka
One minor advantage of old-skool anon. methods is that you can omit the argument declarations if you aren't interested in them, whereas lambdas require the right number of args to be declared. button.Click += delegate { Foo(); }; vs. button.Click += (sender, event) => Foo();Humism
@Earwicker - good point; one I use all the time, so I agree ;-pTopic
S
6

I'd say that the performance differences are usually so small (and in the case of loops, obviously, if you look at the results of the 2nd article (btw, Jon Skeet has a similar article here)) that you should almost never choose a solution for performance reasons alone, unless you are writing a piece of software where performance is absolutely the number one non-functional requirement and you really have to do micro-optimalizations.

When to choose what? I guess it depends on the situation but also the person. Just as an example, some people perfer List.Foreach over a normal foreach loop. I personally prefer the latter, as it is usually more readable, but who am I to argue against this?

Somali answered 23/3, 2009 at 11:14 Comment(2)
no argument from me either :)Meghannmegiddo
I always use foreach when the result is for side-effects. Lambdas for all the LINQ fun, of course.Acerb
R
4

Rules of thumb:

  1. Write your code to be natural and readable.
  2. Avoid code duplications (lambda expressions might require a little extra diligence).
  3. Optimize only when there's a problem, and only with data to back up what that problem actually is.
Rebeccarebecka answered 23/3, 2009 at 11:28 Comment(2)
"Make it correct, make it clear, make it concise, make it fast. In that order" (Wes Dyer blogs.msdn.com/wesdyer/archive/2007/03/01/…)Piddock
That's so true. The first part is often less talked about, "make it correct". In fact quite usually, the first three fall in place well. If you make it correct, its quite readable which in turn will be quite concise.Dang
O
4

Any time the lambda simply passes its arguments directly to another function. Don't create a lambda for function application.

Example:

var coll = new ObservableCollection<int>();
myInts.ForEach(x => coll.Add(x))

Is nicer as:

var coll = new ObservableCollection<int>();
myInts.ForEach(coll.Add)

The main exception is where C#'s type inference fails for whatever reason (and there are plenty of times that's true).

Oceanus answered 23/3, 2009 at 17:57 Comment(0)
H
2

If you need recursion, don't use lambdas, or you'll end up getting very distracted!

Humism answered 23/3, 2009 at 11:35 Comment(5)
Compare to F#: "let rec y f x = f (y f) x" :)Oceanus
I disagree. Recursion is unclear in any approach.Eclipse
@Jerry Nixon - Recursion is sometimes much clearer than the alternative. Try working through mitpress.mit.edu/sicpHumism
@DanielEarwicker I dont think recursive lambda's are distracting. That is one extreme example, which is already quite complicated even if writing as named methods.Dang
Link in answer is outdated.Pus
D
2

Lambda expressions are cool. Over older delegate syntax they have a few advantages like, they can be converted to either anonymous function or expression trees, parameter types are inferred from the declaration, they are cleaner and more concise, etc. I see no real value to not use lambda expression when you're in need of an anonymous function. One not so big advantage the earlier style has is that you can omit the parameter declaration totally if they are not used. Like

Action<int> a = delegate { }; //takes one argument, but no argument specified

This is useful when you have to declare an empty delegate that does nothing, but it is not a strong reason enough to not use lambdas.

Lambdas let you write quick anonymous methods. Now that makes lambdas meaningless everywhere where anonymous methods go meaningless, ie where named methods make more sense. Over named methods, anonymous methods can be disadvantageous (not a lambda expression per se thing, but since these days lambdas widely represent anonymous methods it is relevant):

  1. because it tend to lead to logic duplication (often does, reuse is difficult)

  2. when it is unnecessary to write to one, like:

    //this is unnecessary 
    Func<string, int> f = x => int.Parse(x);
    
    //this is enough
    Func<string, int> f = int.Parse;
    
  3. since writing anonymous iterator block is impossible.

    Func<IEnumerable<int>> f = () => { yield return 0; }; //impossible
    
  4. since recursive lambdas require one more line of quirkiness, like

    Func<int, int> f = null;
    f = x => (x <= 1) ? 1 : x * f(x - 1);
    
  5. well, since reflection is kinda messier, but that is moot isn't it?

Apart from point 3, the rest are not strong reasons not to use lambdas.

Also see this thread about what is disadvantageous about Func/Action delegates, since often they are used along with lambda expressions.

Dang answered 20/12, 2013 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.