C++0x Lambda overhead

10,472

Solution 1

You "know" that function objects incur overhead? Perhaps you should recheck your facts. :)

There is typically zero overhead to using a STL algorithm with a function object, compared with a hand-rolled loop. A naive compiler will have to repeatedly call operator() on the functor, but that is trivial to inline and so in effect, the overhead is zero.

A lambda expression is nothing more than syntactic sugar for a function object. The code is transformed into a function object by the compiler, so it too has zero overhead.

Solution 2

Under the hood,

void f(char delim)
{
  std::for_each( seq.begin()
               , seq.end()
               , [=](const T& obj){std::cout << obj << delim;} );
}

approximately translates into

class __local_class_name {
  char __delim;
public:
  __local_class_name(char delim) : __delim(delim) {}
  void operator()(const T& obj) {std::cout << obj << __delim;}
};

void f(char delim)
{
  std::for_each( seq.begin()
               , seq.end()
               , __local_class_name(delim) );
}

As with all function objects, the overhead is very minimal, since the call can easily be inlined.

Share:
10,472
Gratian Lup
Author by

Gratian Lup

Compiler engineer working on the MSVC C++ compiler optimizer

Updated on June 20, 2022

Comments

  • Gratian Lup
    Gratian Lup about 2 years

    Is there any overhead associated with using lambda expressions in C++0x (under VS2010)?
    I know that using function objects incurs overhead, but I'm referring to expressions that are passed to STL algorithms, for example. Does the compiler optimize the expression, eliminating what seems to appear like a function call? I started to really like lambda expressions, but I'm a bit concerned about the speed penalty.

    Thanks in advance!