mardi 19 mai 2020

emplace_back is faster than allocate once + move in c++11?

I have two fuctions:

f2 - first allocate memory , then move data.

f - deallocate + move = emplace_back.

I am trying to understand what is faster and better to use in terms of performance and code quality?

void f2(const std::vector<std::string>& users) {
    std::vector<std::pair<std::string, int>> userOccurancies(users.size());

    auto userOcIt = userOccurancies.begin();
    for (const auto & user : users) {
        userOcIt->first = std::move(user);
        userOcIt->second = 0;
        userOcIt++;
    }
}

void f(const std::vector<std::string>& users) {
    std::vector < std::pair<std::string, std::size_t>> userCount;
    userCount.reserve(users.size());

    for (auto& user : users) {
        userCount.emplace_back(user, 0);
    }
}

As for performance I tried to check it with MS VS2019 profiler but it always gives me different results if a swap calls of these funcions with each other: f2(users);f(users); and f(users);f2(users); gives different call tree.

Can you help me?

What is faster and better to use in terms of performance and code quality?

I use only c++11.

Aucun commentaire:

Enregistrer un commentaire