2

I'm adding about 25,000 objects to a vector and it's taking too long so I wanted to try and speed it up. Currently I'm adding them in the format:

vector<MyClass> MyVector;
MyVector.push_back(MyClass(Param1, Param2, Parm3, Param4));

As I understand this would involve creating two instances of the object and copying one to the other. Is that correct?

Would it run quicker if I change the vector to pointers like this:

vector<MyClass*> MyVector;
MyVector.push_back(new MyClass(Param1, Param2, Parm3, Param4));

Thanks for any help you can offer.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Clinton Portis
0
vector<MyClass> MyVector;
MyVector.push_back(MyClass(Param1, Param2, Parm3, Param4));

As I understand this would involve creating two instances of the object and copying one to the other. Is that correct?

As I see it, you are creating one instance of 'myclass' which pushed into the vector.

Would it run quicker if I change the vector to pointers like this:

vector<MyClass*> MyVector;
MyVector.push_back(new MyClass(Param1, Param2, Parm3, Param4));

One downfall I see to this method, based on the sheer number of calls to allocate new memory, you should at least be prepared to handle a bad_alloc exception. This method also involves some time for the OS to find an allocate memory for each 'new' operation.

If you want to boost your performance, try taking control of the vector memory allocation using member functions such as: max_size(), capacity(), reserve(), and resize().

Edited by Clinton Portis: vectortastically vectorlicious.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.