I was wondering if there is any difference in performance when you compare/contrast
A) Allocating objects on the heap, putting pointers to those objects in a container, operating on the container elsewhere in the code
Ex:
std::list<SomeObject*> someList;
// Somewhere else in the code
SomeObject* foo = new SomeObject(param1, param2);
someList.push_back(foo);
// Somewhere else in the code
while (itr != someList.end())
{
(*itr)->DoStuff();
//...
}
B) Creating an object, putting it in a container, operating on that container elsewhere in the code
Ex:
std::list<SomeObject> someList;
// Somewhere else in the code
SomeObject newObject(param1, param2);
someList.push_back(newObject);
// Somewhere else in the code
while (itr != someList.end())
{
itr->DoStuff();
...
}
Assuming the pointers are all deallocated correctly and everything works fine, my question is…
If there is a difference, what would yield better performance, and how great would the difference be?
There is a performance hit when inserting objects instead of pointers to objects.
std::listas well as other std containers make a copy of the parameter that you store (forstd::mapboth key and value is copied).As your
someListis a std::list the following line copies your object:It will get copied again when you retrieve it from list. So you are making of copies of the whole object compared to making copies of pointer when using:
You can double check by inserting print statements into Foo’s constructor, destructor, copy constructor.
EDIT: As mentioned in comments,
pop_frontdoes not return anything. You usually get reference to front element withfrontthen youpop_frontto remove the element from list:OR