Performance Benefits of Lambda Expressions

c#, lambda, performance

Solution

Lambda expressions are not more performant, they are just simpler. They are mainly used for:

- Creating delegates

- Creating expressions for LINQ

- Putting local variables in captures for delegates

When creating a delegate, the code that the compiler creates is just like if you would have created a named method, and got a delegate to that method.

Func<int, int> mul = n => n * 2;

compared to:

public static int Mul(int n) {
  return n * 2;
}

Func<int, int> = Mul;

When creating an expression, the compiler creates an expression tree that can either be turned into a delegate or used by a LINQ provider to be translated into something else. The Linq To Sql provider for example would translate the expression into SQL code.

When creating a delegate that uses a local variable that is declared in the method that creates the deleage, a closure object is automatically created where that variable resides, instead of putting the variable on the stack. This is similar to how you would make the variable available to a named method by making it a field in the class where the method is declared.

int x = 2;
Func<int, int> mul = n => n * x;

compared to:

public class Closure {

  public int x;

  public int Mul(int n) {
    return n * x;
  }

}

Closure c = new Closure;
c.x = 2;

Func<int, int> mul = x.Mul;

Problem

I'm pretty new to lambda expressions in C# and I tend not to use them because I don't know what the benefits outside of minimizing code is. Are they more efficient in some/all cases? Or are there any fantastic things they can achieve beyond putting more code within one line?

Original source