mardi 5 mai 2020

Copying std::vector by element more optimized than moving the whole vector

I am trying to pass an std::vector of custom objects by reference to a constructor that copies/moves it to another private std::vector member, but somehow copying it element by element in a for loop generates a smaller program size than when moving the whole vector at once.

Typically I have this code in my constructor:

constructor(std::vector<object*>& newVec)
{
  for(int i=0; i<newVec.size(); ++i)
    this->vec.push_back(newVec[i]); 
}

Which generates a Linux executable that has a smaller size than with using std::move like this:

constructor(std::vector<object*>& newVec)
{
   this->vec=std::move(newVec);
}

Only by switching these two snippets, I pass from 30kB size to 35kB.

PS: The object contained in the vector is different than the constructor object.

Can anyone explain to me why the former version is more optimized than the latter?

Aucun commentaire:

Enregistrer un commentaire