egp*_*bos 3 c++ optimization memory-management c++11
我有一些过早优化的心情,并想知道以下内容.
如果有一个for循环,并且在该循环内部有一个函数的调用,该函数返回一个容器,比如一个向量,其值使用移动语义作为rvalue捕获到循环中的变量中,例如:
std::vector<any_type> function(int i)
{
std::vector<any_type> output(3);
output[0] = i;
output[1] = i*2;
output[2] = i-3;
return(output);
}
int main()
{
for (int i = 0; i < 10; ++i)
{
// stuff
auto value = function(i);
// do stuff with value ...
// ... but in such a way that it can be discarded in the next iteration
}
}
Run Code Online (Sandbox Code Playgroud)
在应用移动语义的情况下,编译器如何处理这种内存(并且该函数不会被内联)?我认为最有效的方法是为函数内部和for循环外部的所有值分配单个内存,这将在每次迭代中被覆盖.
我主要对此感兴趣,因为在我的实际应用程序中,我创建的向量比这里给出的示例大很多.我担心如果我使用这样的函数,分配和销毁过程将占用大量无用的时间,因为我已经知道我将多次使用固定数量的内存.所以,我实际上要问的是,编译器是否有某种方式可以优化到这种形式:
void function(int i, std::vector<any_type> &output)
{
// fill output
}
int main()
{
std::vector<any_type> dummy; // allocate memory only once
for (int i = 0; i < 10; ++i)
{
// stuff
function(i, dummy);
// do stuff with dummy
}
}
Run Code Online (Sandbox Code Playgroud)
特别是我对GCC的实现感兴趣,但也想知道英特尔编译器的用途.
在这里,最可预测的优化是RVO.当函数返回一个对象时,如果它用于初始化一个新变量,编译器可以省略额外的副本并移动到目标上直接构造(这意味着一个程序可以包含两个版本的函数,具体取决于用例) .
在这里,您仍将支付在每个loo迭代中分配和销毁向量内的缓冲区.如果它是不可接受的,你将不得不依赖于其他解决方案,如std :: array,因为你的函数似乎使用固定大小的维度或在循环之前移动向量并重用它.