C++0x Lambda overhead

Gratian Lup picture Gratian Lup · Jul 10, 2010 · Viewed 10.2k times · Source

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!

Answer

jalf picture jalf · Jul 10, 2010

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.