Note that there are some explanatory texts on larger screens.

plurals
  1. POAre lambda functions faster than delegates/anonymous functions?
    primarykey
    data
    text
    <p>I assumed <code>lambda functions</code>, <code>delegates</code> and <code>anonymous functions</code> with the same body would have the same "speed", however, running the following simple program:</p> <pre><code>static void Main(string[] args) { List&lt;int&gt; items = new List&lt;int&gt;(); Random random = new Random(); for (int i = 0; i &lt; 10000000; i++) { items.Add(random.Next()); } Stopwatch watch; IEnumerable&lt;int&gt; result; Func&lt;int, bool&gt; @delegate = delegate(int i) { return i &lt; 500; }; watch = Stopwatch.StartNew(); result = items.Where(@delegate); watch.Stop(); Console.WriteLine("Delegate: {0}", watch.Elapsed.TotalMilliseconds); Func&lt;int, bool&gt; lambda = i =&gt; i &lt; 500; watch = Stopwatch.StartNew(); result = items.Where(lambda); watch.Stop(); Console.WriteLine("Lambda: {0}", watch.Elapsed.TotalMilliseconds); watch = Stopwatch.StartNew(); result = items.Where(i =&gt; i &lt; 500); watch.Stop(); Console.WriteLine("Inline: {0}", watch.Elapsed.TotalMilliseconds); Console.ReadLine(); } </code></pre> <p>I get:</p> <blockquote> <p>Delegate: 4.2948 ms</p> <p>Lambda: 0.0019 ms</p> <p>Anonymous: 0.0034 ms</p> </blockquote> <p>Although negligible, why are these three - apparently identical - methods running at different speeds? What's happening under the hood?</p> <hr> <p><strong>Update:</strong></p> <p>As suggested by the comments, the following "forces" the <code>Where</code> by calling <code>ToList()</code> on it. In addition, a loop is added to offer more run data:</p> <pre><code>while (true) { List&lt;int&gt; items = new List&lt;int&gt;(); Random random = new Random(); for (int i = 0; i &lt; 10000000; i++) { items.Add(random.Next()); } Stopwatch watch; IEnumerable&lt;int&gt; result; Func&lt;int, bool&gt; @delegate = delegate(int i) { return i &lt; 500; }; watch = Stopwatch.StartNew(); result = items.Where(@delegate).ToList(); watch.Stop(); Console.WriteLine("Delegate: {0}", watch.Elapsed.TotalMilliseconds); Func&lt;int, bool&gt; lambda = i =&gt; i &lt; 500; watch = Stopwatch.StartNew(); result = items.Where(lambda).ToList(); watch.Stop(); Console.WriteLine("Lambda: {0}", watch.Elapsed.TotalMilliseconds); watch = Stopwatch.StartNew(); result = items.Where(i =&gt; i &lt; 500).ToList(); watch.Stop(); Console.WriteLine("Inline: {0}", watch.Elapsed.TotalMilliseconds); Console.WriteLine(new string('-', 12)); } </code></pre> <p>The above code results in ~120 ms for each function.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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