7

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.

2
  • Use resize() instead of reserve(), it's a common confusion for newbs. Commented Nov 12, 2015 at 0:28
  • 3
    @πάνταῥεῖ Why? Doesn't resize also default construct the objects? OP is doing the push_back anyway. Maybe I'm confused too :) Commented Nov 12, 2015 at 0:31

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Side comment: emplace_back and push_back are equivalent on rvalues (which is what the OP is using), the latter also moves the object. But I agree that emplace_back clearly states the intention.
"especially what its operator= does" - the push_back approach involves (possibly elided) copy construction of elements (with the default allocator, that's basically a placement new), while the constructor-sized approach involve default construction then assignment, so the relative costs of all those operations is important, as is whether the compiler can optimise away repeated capacity checks and size increments effectively then do as much loop unrolling or other optimisations....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.