Reputation: 351
I would like to create a vector of some complex type, by reading individual elements from a stream. I know the vector size in advance. Is it better to specify the number of elements in the vector constructor or by using reserve method? Which one of these two is better?
int myElementCount = stream.ReadInt();
vector<MyElement> myVector(myElementCount);
for (int i = 0; i < myElementCount; i++)
{
myVector[i] = stream.ReadMyElement();
}
or
int myElementCount = stream.ReadInt();
vector<MyElement> myVector;
myVector.reserve(myElementCount);
for (int i = 0; i < myElementCount; i++)
{
myVector.push_back(stream.ReadMyElement());
}
What about the case where I just create a vector of ints or some other simple type.
Upvotes: 7
Views: 255
Reputation: 17369
It depends on what MyElement
is, especially what its operator=
does, so it's largely the usual "try both and use the faster one for you". There is a third choice, use c++11 and emplace_back
, especially if MyElement
is heavy.
As a datapoint, for int
or double
I found that using the constructor (or resize()
) and []
is faster. Specifically, this way the loop is much easier for the compiler to vectorize.
Upvotes: 6