Reputation: 9619
Consider the following scenario:
std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;
I want AB
to have contents of A
and then the contents of B
in the 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 one of the above methods is more efficient? Why? Is there a different method that is more efficient?
Upvotes: 3
Views: 175
Reputation: 15334
I think the first one will always be faster than the second one because it will only perform one memory allocation and the second one will probably have to reallocate at least once. But my measurements seem to indicate that for sizes less than about 100,000 this is even 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 this is because, not only does this only perform one allocation and no reallocation, it doesn't even need to check if it should do any reallocation. The downside is it may have to zero out all the memory initially, but I think CPUs are good at that.
Upvotes: 1
Reputation: 477040
Approach 1 performs no reallocations, while Approach 2 may reallocate several times, and will in practice most likely reallocate once. So Approach 1 is better.
Upvotes: 3
Reputation: 208343
The first one is probably a bit more efficient since you can guarantee that only one memory allocation will be performed. In the second one, chances are (most implementations do) that an allocation for A.size()
will be done during the vector construction and then the insert
will trigger a second allocation as it needs to grow by B.size()
elements.
Upvotes: 8