'Re: std::vector performance

M

Michiel Salters

Steve said:
Hi,

I'm using a std::vector to store a list of user defined objects. The vector
may have well over 1000 elements, and I'm suffering a performance hit. If I
use push_back I get a much worse perfomance than if I first define the
vector of a given size, then write to the elements with myvec =
....
Yup, you will on any random-access container, since it has to copy
memory. Unfortunately it'll probably do it about as fast or faster
than anything else you could write. Though I've seen dequeue perform
significantly faster than vector on the g++ compiler, for no reason I
could fathom.


deque surprises you, because it is a random-access container that does
not copy its elements. Worst case, it copies a few internal pointers.
One alternative would of course be a vector<Obj*>. Copying 1000
pointers is probably cheap enough. The disadvantage is of cource that
it requires manual memory management. Another alternative is using
a vector of (boost::)smart pointers, which copy almost as fast but
don't require the explicit management.

Regards,
Michiel Salters
 
A

Andre Kostur

(e-mail address removed) (Michiel Salters) wrote in
(e-mail address removed) (James Moughan) wrote in message
Steve said:
Hi,

I'm using a std::vector to store a list of user defined objects.
The vector may have well over 1000 elements, and I'm suffering a
performance hit. If I use push_back I get a much worse perfomance
than if I first define the vector of a given size, then write to
the elements with myvec =
...
Yup, you will on any random-access container, since it has to copy
memory. Unfortunately it'll probably do it about as fast or faster
than anything else you could write. Though I've seen dequeue perform
significantly faster than vector on the g++ compiler, for no reason I
could fathom.


deque surprises you, because it is a random-access container that does
not copy its elements. Worst case, it copies a few internal pointers.
One alternative would of course be a vector<Obj*>. Copying 1000
pointers is probably cheap enough. The disadvantage is of cource that
it requires manual memory management. Another alternative is using
a vector of (boost::)smart pointers, which copy almost as fast but
don't require the explicit management.


Or... .reserve() the size of your vector before doing all of your push_back
()s ....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top