将 lambda 表达式用于事件处理程序
我当前有一个声明如下的页面:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += (o, i) =>
{
//snip
}
}
}
我最近才从 1.1 迁移到 .NET 3.5,因此我习惯在 Page_Load 之外编写事件处理程序。我的问题是;使用 lambda 方法时是否有任何性能缺陷或陷阱需要注意?我更喜欢它,因为它确实更简洁,但我不想牺牲性能来使用它。谢谢。
I currently have a page which is declared as follows:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += (o, i) =>
{
//snip
}
}
}
I've only recently moved to .NET 3.5 from 1.1, so I'm used to writing event handlers outside of the Page_Load. My question is; are there any performance drawbacks or pitfalls I should watch out for when using the lambda method for this? I prefer it, as it's certainly more concise, but I do not want to sacrifice performance to use it. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于编译器会将您的 lambda 表达式转换为等效的委托,因此不会影响性能。 Lambda 表达式只不过是一种语言功能,编译器会将其转换为与您习惯使用的代码完全相同的代码。
编译器会将您的代码转换为如下所示:
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
从性能角度来说,它与命名方法相同。最大的问题是当您执行以下操作时:
它可能会尝试删除不同的 lambda,而将原始的 lambda 保留在那里。所以我们的教训是,除非您也希望能够删除处理程序,否则这很好。
Performance-wise it's the same as a named method. The big problem is when you do the following:
It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.
据我所知,它只是“语法糖”,并且编译成与使用委托语法等相同的东西,我不知道或曾经遇到过任何性能影响。
No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.