title: Understanding the overhead of lambda functions in C++11
body: <p>This was already touched in <a href="https://stackoverflow.com/questions/8611756/why-c-lambda-is-slower-than-ordinary-function-when-called-multiple-times">Why C++ lambda is slower than ordinary function when called multiple times?</a> and <a href="https://stackoverflow.com/questions/3218821/c0x-lambda-overhead">C++0x Lambda overhead</a>
  But I think my example is a bit different from the discussion in the former and contradicts the result in the latter.</p>
  
  <p>On the search for a bottleneck in my code I found a recusive template function that processes a variadic argument list with a given processor function, like copying the value into a buffer.</p>
  
  <pre><code>template &lt;typename T&gt;
  void ProcessArguments(std::function&lt;void(const T &amp;)&gt; process)
  {}
  
  template &lt;typename T, typename HEAD, typename ... TAIL&gt;
  void ProcessArguments(std::function&lt;void(const T &amp;)&gt; process, const HEAD &amp;head, const TAIL &amp;... tail)
  {
    process(head);
    ProcessArguments(process, tail...);
  }
  </code></pre>
  
  <p>I compared the runtime of a program that uses this code together with a lambda function as well as a global function that copies the arguments into a global buffer using a moving pointer:</p>
  
  <pre><code>int buffer[10];
  int main(int argc, char **argv)
  {
    int *p = buffer;
  
    for (unsigned long int i = 0; i &lt; 10E6; ++i)
    {
      p = buffer;
      ProcessArguments&lt;int&gt;([&amp;p](const int &amp;v) { *p++ = v; }, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    }
  }
  </code></pre>
  
  <p>compiled with g++ 4.6 and -O3 measuring with the tool time takes more than 6 seconds on my machine while</p>
  
  <pre><code>int buffer[10];
  int *p = buffer;
  void CopyIntoBuffer(const int &amp;value)
  {
    *p++ = value;
  }
  
  int main(int argc, char **argv)
  {
    int *p = buffer;
  
    for (unsigned long int i = 0; i &lt; 10E6; ++i)
    {
      p = buffer;
      ProcessArguments&lt;int&gt;(CopyIntoBuffer, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    }
  
    return 0;
  }
  </code></pre>
  
  <p>takes about 1.4 seconds.</p>
  
  <p>I do not get what is going on behind the scenes that explains the time overhead and am wondering if I can change something to make use of lambda functions without paying with runtime.</p>