Concatenating two std::vector — which method is more efficient and how/why?

二次信任 提交于 2019-12-30 10:43:15

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/26274745/concatenating-two-stdvector-which-method-is-more-efficient-and-how-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!