c++ - Concatenating two std::vector -- which method is more efficient and how/why? -
consider next scenario:
std::vector<int> a; std::vector<int> b; std::vector<int> ab;
i want ab
have contents of a
, contents of b
in same order.
approach 1:
ab.reserve( a.size() + b.size() ); // preallocate memory ab.insert( ab.end(), a.begin(), a.end() ); ab.insert( ab.end(), b.begin(), b.end() );
approach 2:
std::vector<int> ab ( a.begin(), a.end() ); // calling constructor ab.insert ( ab.end(), b.begin(), b.end() );
which 1 of above methods more efficient? why? there different method more efficient?
i think first 1 faster sec 1 because perform 1 memory allocation , sec 1 have reallocate @ to the lowest degree once. my measurements seem indicate sizes less 100,000 faster:
std::vector<int> ab(a.size() + b.size()); std::copy(a.begin(), a.end(), ab.begin()); std::copy(b.begin(), b.end(), ab.begin() + b.size());
i'm guessing because, not only perform 1 allocation , no reallocation, doesn't need check if should reallocation. downside may have 0 out memory initially, think cpus @ that.
c++ performance concatenation stdvector
No comments:
Post a Comment