简体   繁体   English

复制无状态对象(lambdas)的成本?

[英]Cost of copying stateless objects (lambdas)?

How can one find out if there is a cost in creating an object by copying a lambda?如何通过复制 lambda 来确定创建 object 是否有成本?

template<typename Lambda>
class A {
public:
  A(Lambda lambda) : _lambda(lambda) {} // const Lambda& lambda less efficient?
  auto call(double x) { return _lambda(x); }
private:
  Lambda _lambda; // is const Lambda& _lambda less efficient?
};

I am wondering if having a reference is costly or insignificant (the same as copying the lambda) if the lambda has no state?我想知道如果 lambda 没有 state,那么引用是否成本高昂或微不足道(与复制 lambda 相同)?

How can one find out if there is a cost in creating an object by copying a lambda?如何通过复制 lambda 来确定创建 object 是否有成本?

By testing and profiling with the specific compiler (and switches) you intend to use.通过使用您打算使用的特定编译器(和开关)进行测试和分析。 Anything else is making assumptions about the quality of an implementation you haven't identified.其他任何事情都是对您尚未确定的实施质量做出假设。

References here is going to be ridiculously fragile;这里的引用将非常脆弱。 you will get bugs if you make that a reference.如果你把它作为参考,你得到错误。

Lambdas themselves can choose to be nothing but references to external state; Lambda 本身可以选择仅引用外部 state; just copy them and store them by value.只需复制它们并按值存储它们。 If there is a performance penalty for this in a specific use case, the caller can avoid the copy cost.如果在特定用例中对此有性能损失,调用者可以避免复制成本。

template<class F>
class A {
public:
  explicit A(F f_in) : f(std::move(f_in)) {}
  decltype(auto) call(double x) { return f(x); }
private:
  F f;
};

just a few code-quality changes.只是一些代码质量的改变。

Very simple test show that simple lambda is empty object:非常简单的测试表明简单的 lambda 是空的 object:

template<typename Lambda>
class Test
{
public:
    Test(Lambda _lambda):lambda(_lambda){}

    Lambda lambda;
};

int main()
{
    const auto lambda=[](double x){return x;};
    Test test=lambda;
    //print 1 1
    std::cout<<sizeof(lambda)<<" "<<sizeof(test)<<std::endl;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM