Hendrik Schober
11/10/2008 12:58:00 PM
Uli Kunkel wrote:
> [...]
> I'm wondering if I could use reserve to allocate a few MB and then if
> the size is not enough that the vector grows automatically?
> I read that vector resizing is very costly so I presume that reserving
> just 1KB is not enough.
There's a difference between a vector's size (member functions
'size()'/'resize()') and its capacity ('capacity()'/'reserve()').
The former is related to the number of actual objects in the
vector, the latter to the number of objects the vector is able
to store without having to reallocate.
When you tell a vector to reserve memory for an amount of
elements, it allocates the memory needed (or more), but does
not create the objects. When you tell it to resize to a
specific amount of objects, it will actually contain this
amount of constructed objects (while its capacity might be
higher). The capacity concept allows to write code adding
objects to a vector in the most obvious way (keep appending)
and, if performance or memory fragmentation etc. are issues,
reserve before-hand to reduce or eliminate reallocations. It's
only there for performance-reasons and (besides performance)
has no influence on your algorithm.
So when you know how many objects you will need before-hand,
reserve that amount and then keep appending incoming objects.
If not, strategies depend on your specific problem.
Schobi