Re: STL vector
On 15.11.2011 20:50, Peter Liedermann wrote:
Let "Jumbo" be the name of a class whose instances consume substantial
storage.
A vector of typically 1000 such Jumbo-instances is needed. It must be
sorted by a simple int criterium, but not often.
Is there a substantial performance difference between vector <Jumbo> and
vector <Jumbo *>, provided that everything else is adapted accordingly?
Is there a difference at all?
In general you need to copy the Jumbo objects to put them into the
vector. The copy constructor of Jumbo might be quite expensive if it is
not a POD like type. Is that what you want?
You should also think about the (re)allocations of vector<Jumbo>. A
vector will in general allocate more slots than needed. If Jumbo is
large, then this might be a reasonable amount of memory. Furthermore, a
vector might not start with it's final size. So there are some
reallocations necessary before the vector has it's final size. These
reallocations copy the entire content.
And last but not least, allocating very large objects could cause heap
fragmentation. This might be a reasonable impact, especially on 32 bit
platforms where the virtual memory may be out long before the physical
memory.
On the other side the allocation overhead of large objects is usually
negligible. So almost everything argue for a solution with some references.
As a general rule of thumb large objects should preferably used as
reference type. While small objects should be used as value types.
Personally I would prefer vector<intrusive_ptr<Jumbo>> or some other
smart pointer over vector<Jumbo*>, because it answers the ownership
question more clearly. However, details depend on your application.
Marcel