views:

226

answers:

2

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!

+4  A: 

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.

sbi
Please mind that `delim` has to be explicitly captured.
Dario
He does; `[=]` indicates that all local objects should be captured by value.
Dennis Zickefoose
@Dennis: Only jalf added the `=`, so @Dario was right. `:(` @jalf: Thanks. My excuse is that I hadn't had the time yet to play with this, so it's all typed from hearsay.
sbi
yeah, I should probably have left a comment saying I added it. :) But yeah, `[=]` captures everything by value. We could have used `[delim]` as well, to capture that variable specifically. Btw, I +1'ed your answer. :)
jalf
__local_class_name would be a local class in the scope of the function f. C++0x allows local class instances to be used as parameters to function templates (they are not allowed current standard). It's also worth noting that the class name is generated by the compiler for each lambda and you can not name the type of the lambda yourself.
snk_kid
@snk_kid: I was wondering about whether that class would be function-local or not. In the end I decided that, since didn't know, and since the name was supposed to be unique anyway, I would err to the safe side and put it into namespace scope. Can you cite chapter and verse? If so, I'd go and move it.
sbi
@jalf: No problem about the edit. And I figured that you'd give me an up-vote for this as soon as I saw you around. However, I was first in up-voting you. `:)`
sbi
+10  A: 

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.

jalf