简体   繁体   English

连接两个std :: vector - 哪种方法更有效,怎么/为什么?

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

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. 我希望AB以相同的顺序包含A的内容,然后是B的内容。

Approach 1: 方法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: 方法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? 是否有更高效的不同方法?

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. 在第二个中,很可能(大多数实现都会)在向量构造期间完成A.size()的分配,然后insert将触发第二个分配,因为它需要通过B.size()元素增长。

Approach 1 performs no reallocations, while Approach 2 may reallocate several times, and will in practice most likely reallocate once. 方法1个执行重新分配,而方法2可以重新分配几次,将在实践中极有可能重新分配一次。 So Approach 1 is better. 方法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: 我的测量结果似乎表明,对于小于约100,000的尺寸,这甚至更快:

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. 缺点是最初可能必须将所有内存归零,但我认为CPU很擅长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM