title: C# lambda allocation and collection
body: <p>I saw <a href="https://stackoverflow.com/q/38726231/1488067">this question</a> today about some performance difference regarding <code>ConcurrentDictionary</code> methods, and I saw it as a premature micro-optimization.</p>
  
  <p>However, upon some thought, I realized (if I am not mistaken), that each time we pass a lambda to a method, CLR needs to allocate the memory, pass the appropriate closure (if needed), and then collect it some time later.</p>
  
  <p>There are three possibilities:</p>
  
  <ol>
  <li><p>Lambda without a closure:</p>
  
  <pre><code>// the lambda should internally compile to a static method, 
  // but will CLR instantiate a new ManagedDelegate wrapper or
  // something like that?
  return concurrent_dict.GetOrAdd(key, k =&gt; ValueFactory(k));
  </code></pre></li>
  <li><p>Lambda with a closure:</p>
  
  <pre><code>// this is definitely an allocation
  return concurrent_dict.GetOrAdd(key, k =&gt; ValueFactory(k, stuff));
  </code></pre></li>
  <li><p>Outside check (like checking the condition before the lock):</p>
  
  <pre><code>// no lambdas in the hot path
  if (!concurrent_dict.TryGetValue(key, out value))
      return concurrent_dict.GetOrAdd(key, k =&gt; ValueFactory(k));
  </code></pre></li>
  </ol>
  
  <p>Third case is obviously allocation-free, the second one will need an allocation. </p>
  
  <p>But is the first case (lambda which doesn't have a capture) completely allocation-free (at least in newer CLR versions)? Also, is this an implementation detail of the runtime, or something specified by the standard?</p>