Sossenbinder
Sossenbinder

Reputation: 5292

When using Lambdas, is it more performant to pass by value through the capture clause or through passing as a parameter?

This question just came to my mind, and I don't really know how to figure it out.

Let me show you what I mean:

int x = 1;

auto lambda1 = [x](){

 // do something with x, not specified here though
}

auto lambda2 = [](int x){

  // do something with x, not specified here though
}

lambda1();
lambda2(x);

Let's assume we would only have either lambda1 or lambda2 at a given time.

Which function would be faster in that case? I am pretty sure the difference is minimal, if there is even any difference at all, but this just caught my interest and I'd really like to know!

This might be very stupid to ask if we are only working with one int, but there might be a measurable difference in larger scaled lambdas.

Upvotes: 1

Views: 100

Answers (1)

bobah
bobah

Reputation: 18864

The first one translates to

struct _ {
    int x;
    _(int x_): x(x_) {}
    void operator()() const {...}
};

The second one translates to

struct _ {
    _() = default;
    void operator()(int x) const {...}
};

The former may have various effects* around the closure construction site, the latter may have the very same effects* around the closure call site.

* - depends

Upvotes: 3

Related Questions