Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lambda object construction cost a lot?

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.

like image 609
heLomaN Avatar asked Aug 27 '26 18:08

heLomaN


2 Answers

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);
like image 113
YSC Avatar answered Aug 30 '26 10:08

YSC


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.

like image 36
villintehaspam Avatar answered Aug 30 '26 09:08

villintehaspam