使用 Lambda 时,通过捕获子句按值传递还是通过作为参数传递来传递性能更高

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

本文关键字:参数传递 性能 Lambda 使用 按值传递 子句      更新时间:2023-10-16

这个问题刚刚浮现在我的脑海中,我真的不知道该怎么弄清楚。

让我告诉你我的意思:

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);

假设在给定时间我们只有 lambda1 或 lambda2。

在这种情况下,哪个功能会更快?我很确定差异很小,如果有任何差异的话,但这引起了我的兴趣,我真的很想知道!

问我们是否只使用一个 int 可能非常愚蠢,但在更大比例的 lambda 中可能存在可测量的差异。

第一个翻译为

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

第二个翻译为

struct _ {
    _() = default;
    void operator()(int x) const {...}
};
前者可能在关闭施工现场周围产生

各种影响*,后者可能在关闭呼叫现场周围产生完全相同的影响*。

*-取决于