考虑以下代码:
// Classic version
template <class It>
It f(It first, It last)
{
using value_type = It::value_type;
auto lambda = [](value_type x){return x > 10 && x < 100;};
return std::find_if(first, last, lambda);
}
// Static version
template <class It>
It f(It first, It last)
{
using value_type = It::value_type;
static auto lambda = [](value_type x){return x > 10 && x < 100;};
return std::find_if(first, last, lambda);
}两者在性能上有什么区别吗?一个lambda函数的构建时间是多少?静态版本在性能方面是否更好,因为lambda只构建了一次?
发布于 2015-12-01 01:48:50
构建无捕获的lambda类似于构建一个空的struct。一个现代的编译器应该能够完全地优化它。
例如,请参见此简单程序的程序集输出:
int main(int argc, const char* argv[])
{
auto l = [](int i){ return i*i; };
return l(argc);
} 装配(gcc 5.2.0,从-O1,LIVE开始):
main:
movl %edi, %eax
imull %edi, %eax
ret如你所见,没有任何残留的羊驼,等等。它是完全内联的。
虽然您的特定用例可能需要更多的分析,但是在静态和非静态lambdas之间可能没有可测量的差别。
https://stackoverflow.com/questions/34011065
复制相似问题