Re: stl vector performance
barbaros wrote:
Hello,
Is there any advantage in performing a reserve operation before
inserting a large number of zeroes in an empty vector ?
Let me be more specific. In the code below, does the second line bring
any increase in performance ?
vector<float> v;
v.reserve(1000);
v.insert(v.end(),1000,0.0);
The implementation of std::vector in your compiler would have to be
really, really stupid if its insert() function didn't allocate memory
for all the inserted elements in one single step, given that it knows
exactly how many of them are being inserted.
If you inserted using a forward iterator range, then there might be a
benefit in reserving space for the new elements (if you know how many of
them there are) because the library has no way of knowing in advance
(ie. before traversing the iterator range) how many elements will be
inserted. (If you use a random access iterator range, then some library
implementations might use template magic to detect that this is the
case, in which case it can allocate the necessary memory in advance.
However, this might not be the case with all possible STL implementations.)