我有一个代码,我有两个选项,定义lambda out of loop以节省lambda创建开销或在循环内定义它以保持小范围.
这个选择是否至关重要并会产生重大影响?
这两种选择的利弊是什么?
什么是最佳做法?
#include <iostream>
#include <string>
#include <vector>
#include <memory>
int main()
{
std::vector<std::function<void()>> functors;
auto func = [] () { std::cout << "Hello world I am doing some action"; };
//some code here
for(int i = 0; i < 100; ++i)
{
// some code here
functors.push_back(func);
// some code here
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:简化的例子
int main()
{
auto sum = [](const int x, const int y) { return x + y; };
for(int i = 0; i < 100; ++i)
{
std::cout << sum(i, i + 1) << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
Arm*_*yan 10
对于每个lambda表达式,编译器将为其创建一个operator ()重载的结构.每次控件通过lambda时都不会创建结构,因此就生成的代码而言,无论是在循环内部还是外部定义它都无关紧要.因此,保持本地化.
作为一般规则,不要过度思考这些虚幻的优化问题.最有可能的是,性能瓶颈将出现在算法复杂性中.
| 归档时间: |
|
| 查看次数: |
3238 次 |
| 最近记录: |