doctopus
doctopus

Reputation: 5657

Is slicing a vector faster than copying each element into a new vector?

Let's say I have a vector of 10 ints and I want to create 2 subvectors each of 5 elements.

Is it faster if I slice the vector like this:

vector<int> vec({0,1,2,3,4,5,6,7,8,9});
auto x = vec.begin();
vector<int> vec2(x, x+5);
x += 5;
vector<int> vec3(x, x+5);

As opposed to this?

vector<int> vec({0,1,2,3,4,5,6,7,8,9});
vector<int> vec2;
for (int i = 0; i < 5; i++) {
    vec2.push_back(vec[i]);
}
vector<int> vec3;
for (int i = 5; i < 10; i++) {
    vec3.push_back(vec[i]);
}

Upvotes: 1

Views: 211

Answers (1)

Ghasem Ramezani
Ghasem Ramezani

Reputation: 2888

First will be faster, because in the first way std::vector will allocate all needed memory in first construction, but in second way with std::vector<T>::push_back need to allocate memory and increase the underlying array size which is painful.

Here is a little benchmark: https://quick-bench.com/q/dXoWJhTzYDgNnIPFj-vla4pZ_PU

enter image description here

Upvotes: 4

Related Questions