jeudi 25 avril 2019

std::vector push_back unique_ptr vs shared_ptr performance

Shouldn't push_back be faster on a simple std::vector < unique_ptr > vs std::vector< shared_ptr > ??

int vecElements=100000;
        std::vector<std::shared_ptr<B>> vecshared, vecshared2;
        for (int i=0;i<vecElements;++i)
        {
            vecshared.push_back(std::make_shared<B>(i));
        }

        ////////////////////////////////////////////////////
        //create new Bs and push them back using the default copy construciton of std::vector
        std::vector<std::unique_ptr<B>> vec;
        for (int i=0;i<vecElements;++i)
        {
            vec.push_back(std::make_unique<B>(i));
        }

        std::vector<std::unique_ptr<B>> vec2;
        auto start = std::chrono::system_clock::now();
        for (int i=0;i<vecElements;++i)
        {
            //the "move constructor of the std::vector" is forced
            //to be called to move the unique_ptr object vec[i]
            //each of vec2's element is created via move contruction (using the std vector move)
            vec2.push_back(std::move(vec[i]));
        }
        auto end = std::chrono::system_clock::now();
        auto totalSecs = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
        //auto elapsed = end - start;
        std::cout <<"\n std::move unique ptrs test= " <<totalSecs << '\n';

        //Now test without move
        start = std::chrono::system_clock::now();
        for (int i=0;i<vecElements;++i)
        {
            //push back copy- normal (copy the shared_ptrs), no move imposed as they are shared
            vecshared2.push_back(vecshared[i]);

            //the move constructor of the std::vector is forced
            //to be called to move the shared_ptr object vec[i]
        }
        end = std::chrono::system_clock::now();
        totalSecs = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
        //auto elapsed = end - start;
        std::cout <<"\n NO std::move - shared ptrs test= " <<totalSecs << '\n';

This is what the result is!
std::move unique ptrs test= 25 NO std::move - shared ptrs test= 9

I would expect shared ptrs to be slower because of reference counting, no?

Aucun commentaire:

Enregistrer un commentaire