Update: Due to a glitch in my code I miscalculated the difference. It has been updated. See full history of the code in the Gist. The outcome is still essentially the same :)

I was talking with David Fowler when he mentioned something I found surprising: “Lambdas are more efficient than Method Groups”. My initial reaction was that he was entirely wrong, but he explained why and then I decided to do some analysis. Here’s what I found.

I wrote a simple program that would pass a method group in to a method in a big loop:

for (int i = 0; i < Iterations; i++)
{
Call(Dump);
}

And later on, it tried the same with a simple lambda

for (int i = 0; i < Iterations; i++)
{
Call(s => Dump(s));
}

Where Call takes an Action<string> and Dump takes a single string argument and just does nothing:

private static void Call(Action<string> act)
{
act("Hi!");
} private static void Dump(string str)
{ }

See the full code for the program as a Gist.

I put in some simple Stopwatch-based timing and Console.ReadLine calls to allow me to advance the app through the steps slowly. The results from the Stopwatch (which timed the whole process and took an average) were interesting on their own. I pre-JIT the methods by calling them outside the loops first, and with 100,000,000 iterations, I got this output:

Running Method Group Test
Finished Method Group Test
Elapsed: 1.5171E+006ns
Average: 1.5171E-002ns
High-Precision? Yes
Press Enter to Continue Running Lambda Test
Finished Lambda Test
Elapsed: 9.9125E+005ns
Average: 9.9125E-003ns
High-Precision? Yes
Press Enter to End

The lambda case is noticibly faster! Note the difference in exponent (we’re dealing with tiny numbers). Ok, so not much faster, but still, that’s a significant result.

Now, what about memory. So I pulled up perfmon and added the .NET “Allocated Bytes/sec” counter. I’m not sure if that’s the right one, but it certainly seemed to illustrate the point. This is what I saw:

The big spike at the beginning (highlighted in Orange) is the Method Group round. The flat line (highlighted in Green) is the Lambda round. This must be where the problem lies.

Sure enough, looking at the code, we see something interesting. To simplify, I’ve made simple instance methods that just perform the call with a method group and a lambda (see the Gist). Now to decompile them.

.method private hidebysig instance void MethodGroup() cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldnull
L_0002: ldftn void Curious.Program::Dump(string)
L_0008: newobj instance void [mscorlib]System.Action`1<string>::.ctor(object, native int)
L_000d: call void Curious.Program::Call(class [mscorlib]System.Action`1<string>)
L_0012: nop
L_0013: ret
}

First the one with the Method Group (above). Hmm… at L_0008 we see that we’re creating a new delegate and putting the function pointer to Dump in. Make sense. So why doesn’t the lambda version create the same amount of memory?

.method private hidebysig instance void Lambda() cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldsfld class [mscorlib]System.Action`1<string> Curious.Program::CS$<>9__CachedAnonymousMethodDelegate5
L_0006: brtrue.s L_001b
L_0008: ldnull
L_0009: ldftn void Curious.Program::<Lambda>b__4(string)
L_000f: newobj instance void [mscorlib]System.Action`1<string>::.ctor(object, native int)
L_0014: stsfld class [mscorlib]System.Action`1<string> Curious.Program::CS$<>9__CachedAnonymousMethodDelegate5
L_0019: br.s L_001b
L_001b: ldsfld class [mscorlib]System.Action`1<string> Curious.Program::CS$<>9__CachedAnonymousMethodDelegate5
L_0020: call void Curious.Program::Call(class [mscorlib]System.Action`1<string>)
L_0025: nop
L_0026: ret
}

Well, it certainly does more. But the key parts start at L_0001. The first thing this code does is check if the “CS$<>9__CachedAnonymousMethodDelegate5” member has a value. If not, it fills it in, at L_0014. But if it DOES have a value, the code just invokes that cached value! BINGO! The Method Group version allocates a new object every single time it is run whereas the lambda version uses an instance (or static, as necessary) field to cache the delegate.

So, what does this mean for you? Well, probably not much. Notice that all these numbers were tiny, so we’re talking about micro-optimizations. In fact, the most important take-away here is to remember that just because something seems faster, doesn’t mean it is faster. In David’s case, he discovered this in SignalR because they have a non-trivial number of lambdas allocated per connection, and there can be a LOT of connections. I know that I’ll probably switch to using Lambdas, just because it doesn’t seem to have any ill effects and if it saves us a few bytes, why not.

Please do note that I’m no performance expert. If you see a problem in this post, please tell me! It’s possible I’ve gotten this completely wrong somehow, so if this kind of performance is crucial to your app, you should definitely do your own profiling! And remember, the only way to make performance gains is to measure measure measure. You can’t just eyeball perf ;).

refer to:http://vibrantcode.com/2013/02/19/lambdas-vs-method-groups/

lambdas vs. method groups的更多相关文章

  1. What's New for Visual C# 6.0

    https://msdn.microsoft.com/en-us/library/hh156499.aspx nameof You can get the unqualified string nam ...

  2. C#6.0 VS2015

    https://msdn.microsoft.com/en-us/library/hh156499(v=vs.140).aspx This page lists key feature names f ...

  3. New Language Features in C# 6

    Source:https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6 This document describes ...

  4. TestNG官方文档中文版(5)-测试方法/类和组

    5 - Test methods, Test classes and Test groups 5.1 - Test groups TestNG容许执行复杂的测试方法分组.不仅可以申明方法属于组,而且可 ...

  5. Java 8特性探究(1):通往lambda之路与 lambda表达式10个示例

    本文由 ImportNew 函数式接口 函数式接口(functional interface 也叫功能性接口,其实是同一个东西).简单来说,函数式接口是只包含一个方法的接口.比如Java标准库中的ja ...

  6. 【转】Java 8十个lambda表达式案例

    1. 实现Runnable线程案例 使用() -> {} 替代匿名类: //Before Java 8: new Thread(new Runnable() { @Override public ...

  7. Kotlin 语言高级安卓开发入门

    过去一年,使用 Kotlin 来为安卓开发的人越来越多.即使那些现在还没有使用这个语言的开发者,也会对这个语言的精髓产生共鸣,它给现在 Java 开发增加了简单并且强大的范式.Jake Wharton ...

  8. TestNG官方文档中文版(2)-annotation(转)

    1. 介绍    TestNG是一个设计用来简化广泛的测试需求的测试框架,从单元测试(隔离测试一个类)到集成测试(测试由有多个类多个包甚至多个外部框架组成的整个系统,例如运用服务器). 编写一个测试的 ...

  9. [LINQ]查询关键字

    摘自https://msdn.microsoft.com/zh-cn/library/bb310804.aspx,方便以后翻阅. from子句 查询表达式必须以 from 子句开头.另外,查询表达式还 ...

随机推荐

  1. 一头扎进 Java IO中-------java IO文件

    Java IO: 文件 在Java应用程序中,文件是一种常用的数据源或者存储数据的媒介.所以这一小节将会对Java中文件的使用做一个简短的概述.这篇文章不会对每一个技术细节都做出解释,而是会针对文件存 ...

  2. [中英对照]The Art Of Reporting Bugs | 报bug的艺术

    前言:因为最近要给兄弟Team分享一下如何有效地报告bug, 故多做一做功课.下面给出一篇博客的中英文对照翻译. The Art Of Reporting Bugs | 报bug的艺术 My init ...

  3. [转]Support Composite Key in ASP.NET Web API OData

    本文转自:https://code.msdn.microsoft.com/Support-Composite-Key-in-d1d53161 he default EntitySetControlle ...

  4. var、let、const的区别,以及作用范围。

    在es5中一般经常使用的变量有两个级别,一个是用var声明的全局级别的变量,另外一个是函数级别是用var生命在函数内的.本文中将详细讲解我对es6中的const和let的区别. let的使用以及作用范 ...

  5. SQL Serever学习9——基础查询语句

    SQL语言概述 SQL是结构化查询语言(Structure Query Language),1974年提出,1979年被IBM实现,SQL语言已经成为关系型数据库的标准语言. 包括: DDL数据定义语 ...

  6. 可变参数的lambda表达式

    delegate int mydelegate(params int[] a); class Program { static void Main(string[] args) { //接收可变参数的 ...

  7. node错误集合

    1.端口被占用 node .\app.js events.js:167 throw er; // Unhandled 'error' even 解决办法:8888端口被占用了,更改一个端口就好 2. ...

  8. FE面试题库

    一.HTML 序号 面试题目 难度等级 回答要点 H1 简述编写HTML需要注意哪些事项? ☆ DOCTYPE.charset.viewport.语义化.CSS与JS的位置.DOM层级.结构样式行为的 ...

  9. 面向对象(基础oop)之进入继承

    大家好,我叫李京阳,,很高兴认识大家,之所以我想开一个自己的博客,就是来把自己所了解的知识点通过自己的话写一下,希望被博客园的朋友们点评和一起讨论一下,也希望从博客园中多认识一些软件开发人员!现在我开 ...

  10. 撩课-Web大前端每天5道面试题-Day8

    1. 说说你对作用域链的理解? 作用域链的作用是保证执行环境里 有权访问的变量和函数是有序的, 作用域链的变量只能向上访问, 变量访问到window对象即被终止, 作用域链向下访问变量是不被允许的; ...