简体   繁体   English

Lambda表达式的性能优势

[英]Performance Benefits of Lambda Expressions

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. 我对C#中的lambda表达式很新,我倾向于不使用它们,因为我不知道最小化代码的好处是什么。 Are they more efficient in some/all cases? 它们在某些/所有情况下都更有效吗? Or are there any fantastic things they can achieve beyond putting more code within one line? 或者除了将更多代码放在一行之外,还有什么奇妙的东西可以实现吗?

Are they more efficient in some/all cases? 它们在某些/所有情况下都更有效吗?

Lambda expressions, in general, aren't about performance efficiency as much as about developer efficiency. 一般而言,Lambda表达式与性能效率无关,与开发人员效率无关。

They are a way to create methods in a far more productive manner than writing the methods by hand. 与手工编写方法相比,它们是一种以更高效的方式创建方法的方法。 That being said, they do nothing to (directly) improve performance. 话虽如此,他们没有(直接)改善绩效。

However, by properly utilizing frameworks which work in a functional manner (ie: using LINQ), you can increase your likelihood of writing efficient code, as the framework itself is likely highly optimized. 但是,通过正确使用以功能方式工作的框架(即:使用LINQ),您可以提高编写高效代码的可能性,因为框架本身可能已经过高度优化。

Lambda expressions are not more performant, they are just simpler. Lambda表达式不是更高效,它们更简单。 They are mainly used for: 它们主要用于:

  • Creating delegates 创建代表
  • Creating expressions for LINQ 为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. 在创建表达式时,编译器会创建一个表达式树,该表达式树可以转换为委托,也可以由LINQ提供程序用于转换为其他内容。 The Linq To Sql provider for example would translate the expression into SQL code. 例如,Linq To Sql提供程序会将表达式转换为SQL代码。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM