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

笑着哭i 提交于 2019-12-01 09:26:01

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.

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.

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.

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