Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A lambda expression <em>is</em> an anonymous function. "Anonymous function" refers to either a lambda expression or an anonymous method (which is what <em>you've</em> called a "delegate" in your code).</p> <p>All three operations are using delegates. The second and third are both using lambda expressions. All three will execute in the same way, with the same performance characteristics.</p> <p>Note that there <em>can</em> be a difference in performance between:</p> <pre><code>Func&lt;int, int&gt; func = x =&gt; ...; for (int i = 0; i &lt; 10000; i++) { CallFunc(func); } </code></pre> <p>and</p> <pre><code>for (int i = 0; i &lt; 10000; i++) { CallFunc(x =&gt; ...) // Same lambda as before } </code></pre> <p>It depends on whether the compiler is able to cache the delegate created by the lambda expression. That will in turn depend on whether it captures variables etc.</p> <p>For example, consider this code:</p> <pre><code>using System; using System.Diagnostics; class Test { const int Iterations = 1000000000; static void Main() { AllocateOnce(); AllocateInLoop(); } static void AllocateOnce() { int x = 10; Stopwatch sw = Stopwatch.StartNew(); int sum = 0; Func&lt;int, int&gt; allocateOnce = y =&gt; y + x; for (int i = 0; i &lt; Iterations; i++) { sum += Apply(i, allocateOnce); } sw.Stop(); Console.WriteLine("Allocated once: {0}ms", sw.ElapsedMilliseconds); } static void AllocateInLoop() { int x = 10; Stopwatch sw = Stopwatch.StartNew(); int sum = 0; for (int i = 0; i &lt; Iterations; i++) { sum += Apply(i, y =&gt; y + x); } sw.Stop(); Console.WriteLine("Allocated in loop: {0}ms", sw.ElapsedMilliseconds); } static int Apply(int loopCounter, Func&lt;int, int&gt; func) { return func(loopCounter); } } </code></pre> <p>The compiler is smart, but there's still a difference. Using Reflector, we can see that <code>AllocateInLoop</code> is effectively compiled to:</p> <pre><code>private static void AllocateInLoop() { Func&lt;int, int&gt; func = null; int x = 10; Stopwatch stopwatch = Stopwatch.StartNew(); int sum = 0; for (int i = 0; i &lt; Iterations; i++) { if (func == null) { func = y =&gt; y + x; } sum += Apply(i, func); } stopwatch.Stop(); Console.WriteLine("Allocated in loop: {0}ms", stopwatch.ElapsedMilliseconds); } </code></pre> <p>So still only a single delegate instance is created, but there's extra logic within the loop - an extra nullity test on each iteration, basically.</p> <p>On my machine that makes about a 15% difference in performance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload