vendredi 31 mars 2017

Is assigning const reference is actually faster than move semantics?

Consider following C++ code:

using DataType = std::vector<int>;
class Foo
{
private: 
    DataType m_data;
public:
    void setConstLvalue (const DataType& data) 
    { 
        m_data = data; 
    }
    void setRvalueMove  (DataType&& data)      
    {
        m_data = std::move(data); 
    }
};

I thought setRvalueMove one would be faster, of course. And yes, I was right.

But it was only faster if I pass r-value vector<int> to both methods. This time, I explicitly declared another vector<int> and pass through both methods(l-value), setConstLvalue was about 3 times faster, optimized or not.

Live Demo

My questions

  1. Why is setConstLvalue is faster than setRvalueMove, if I pass l-value through them?
  2. And why not if I pass r-value?
  3. Is time complexity of vector move-assignment is constant, or linear in size?

Aucun commentaire:

Enregistrer un commentaire