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!
2 Answers 2
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.
6 Comments
std::functions significantly increases the size of the executable, at least in VS2010. I just performed this test.std:string incurs a lot of overhead too. But that wasn't what the question, or my answer, were about. They were about function objects and lambdas. std::function is neither.std::function is a wrapper class, an abstraction over all callable objects, whether function pointers or functors. And it is not free to use. But if you avoid the wrapper, and just use a functor, or a lambda, directly, there is zero overheadT can take a lambda as a parameter. Of course, for a non-template function, you have to specify the actual parameter type, and you can't do that if the type is a lambda, so in that case, you have to wrap it in a std::function or similar.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.
7 Comments
[=] indicates that all local objects should be captured by value.=, 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.[=] captures everything by value. We could have used [delim] as well, to capture that variable specifically. Btw, I +1'ed your answer. :)Explore related questions
See similar questions with these tags.
std::functionobject (don't need to use boost, since that has been adopted into the 0x standard