mercredi 9 octobre 2019

Why returning a vector by reference is much faster than returning by move?

I have two similar methods, both of which take a std::vector by reference and then one of them tries to return it by reference(since lifetime is satisfied) and another one returns by move. In both cases, I don't need the passed vector afterwards, it's just to satisfy syntactical requirement.

Both functions look like -

std::vector<unique_ptr<Item>> func_returns_move(std::vector<unique_ptr<Item>> &items) {
    items.erase(std::remove_if(items.begin(), items.end(),
    [&](const std::unique_ptr<Item> &item) {
        return item->age > 20;
    }), items.end());
    return move(items);
}


std::vector<unique_ptr<Item>>& func_returns_ref(std::vector<unique_ptr<Item>> &items) {
    items.erase(std::remove_if(items.begin(), items.end(),
    [&](const std::unique_ptr<Item> &item) {
        return item->age > 20;
    }), items.end());
    return items;
}

From my assumption, there shouldn't be much difference here as the only differing line is the last one - one returns by ref and another directly moves. At first I thought maybe the difference was due to move creating one temporary object which might malloc by default or something, that will be the result of function like result = func_returns_move(...) but it should be constant time which is not the case here. The time spent is proportional to number of elements in vector. So I'm failing to understand what is causing more execution in return by std::move case.


Timings are as follows -

FUNC_RETURNS_MOVE: 50
FUNC_RETURNS_REF: 5

Testing program here - https://godbolt.org/z/5Y8Mcw

Aucun commentaire:

Enregistrer un commentaire