Filling a vector with a known number of elements: specify its size in the constructor or using the stock method?

I would like to create a vector of some complex type by reading individual elements from a stream. I know the size of the vector in advance. Is it better to specify the number of elements in the vector constructor or use the fallback method? Which 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()); } 

How about when I just create an ints vector or some other simple type.

+7
c ++ vector std
source share
1 answer

It depends on what MyElement , especially what its operator= does, so it is basically the usual "try both and use a faster one for you." There is a third option, 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. In particular, in this way the loop is much easier to vectorize the compiler.

+6
source share

All Articles