Before you do ANYTHING profile the code and get a benchmark. After you make a change profile the code and get a benchmark. Compare the benchmarks. If you do not do this, you're rolling dice. Is it faster? Who knows.
Profile profile profile.
With push_back
you have two main concerns:
- Resizing the
vector
when it fills up, and
- Copying the object into the
vector
.
There are a number of improvements you can make to the resizing cost cost of push_back
depending on how items are being added.
Strategic use of reserve
to minimize the amount of resizing, for example. If you know how many items are about to be added, you can check the capacity
and size
to see if it's worth your time to reserve
to avoid multiple resizes. Note this requires knowledge of vector
's expansion strategy and that is implementation-specific. An optimization for one vector
implementation could be a terribly bad mistake on another.
You can use insert
to add multiple items at a time. Of course this is close to useless if you need to add another container into the code in order to bulk-insert.
If you have no idea how many items are incoming, you might as well let vector
do its job and optimize HOW the items are added.
For example
void addToContainer(Object object) // pass by value. Possible copy
{
container.push_back(object); // copy
}
Those copies can be expensive. Get rid of them.
void addToContainer(Object && object) //no copy and can still handle temporaries
{
container.push_back(std::move(object)); // moves rather than copies
}
std::string
is often very cheap to move.
This variant of addToContainer
can be used with
addToContainer({ "Fira", "+5 ATTACK" });
addToContainer({ "Potion", "+10 HP" });
and might just migrate a pointer and as few book-keeping variables per string
. They are temporaries, so no one cares if it will rips their guts out and throws away the corpses.
As for existing Object
s
Object o{"Pizza pop", "+5 food"};
addToContainer(std::move(o));
If they are expendable, they get moved as well. If they aren't expendable...
void addToContainer(const Object & object) // no copy
{
container.push_back(object); // copy
}
You have an overload that does it the hard way.
Tossing this one out there
If you already have a number of items you know are going to be in the list, rather than appending them all one at a time, use an initialization list:
vector<Object> container{
{"Vorpal Cheese Grater", "Many little pieces"},
{"Holy Hand Grenade", "OMG Damage"}
};