For some purpose, one may declare a functor in a frequently callee function. Will the construction of the functor cost a lot, or just comparable to defining a plain struct?
void f() {
static int x = 0;
auto a = [&](){ x += 1;};
for (auto i = 0, i < 10; ++i) {
a();
}
}
// somewhere else call f thousands of times
f()
Edit Updated the sample code.
A lambda is generally cheap.
SomeType var;
auto lambda = [var](){ /* ... */ }
here, lambda is just an instance of an anonymous type. The type itself is processed at compile-time, so no worries. What happens at run-time though is the capture of variables (here var). When a capture is done by value, the value itself is copied into the lambda instance. This is what costs. When a capture is done by reference, the reference is copied into the lambda, which is cheap.
For your information, the code displayed is equivalent to:
SomeType var;
struct anonymous {
anonymous(SomeType st) : st(st) {}
void operator()() { /* .... */ }
private:
SomeType st;
} lambda(var);
The answer is as always: it depends.
Depending on what the lambda looks like the compiler may be able to make it into a function pointer, or just inline it. For more complicated stuff the construction cost will be similar to a struct.
You should always measure what performance you get for your particular use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With