【问题标题】:When using Lambdas, is it more performant to pass by value through the capture clause or through passing as a parameter?使用 Lambdas 时,通过捕获子句按值传递还是通过作为参数传递更高效?
【发布时间】:2023-03-09 09:41:01
【问题描述】:

这个问题我刚刚想到,我真的不知道如何解决。

让我告诉你我的意思:

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 中可能存在可测量的差异。

【问题讨论】:

  • 我不认为这与哪个版本更快有关。她们不一样。你不能用第一个做你可以用另一个做的。
  • 您无法真正比​​较两者,它们做不同的事情。出于性能原因,请勿使用其中一种,请根据您的需要进行选择。

标签: c++ lambda


【解决方案1】:

第一个翻译成

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

第二个翻译成

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

前者可能在闭包构建站点周围产生不同的效果*,后者可能在闭包调用站点周围具有完全相同的效果*。

* - 取决于

【讨论】:

猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 2012-07-05
  • 2015-02-24
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
相关资源
最近更新 更多