Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shrink_to_fit() vs swap trick

I have a game where certain game objects spawn all at once and then despawn as they get destroyed/killed. The game objects are elements in an std::vector, and I'd like to minimize memory usage. I'm used to the swap trick,

std::vector<gameObject>(gameObjectVector.begin(), gameObjectVector.end()).swap(gameObjectVector);

but I noticed the inbuilt shrink_to_fit() from C++11. However, it has linear complexity while the swap trick is constant. Isn't the swap trick superior in every way?

like image 430
Andreas Winther Moen Avatar asked Apr 27 '17 20:04

Andreas Winther Moen


2 Answers

The swap trick isn't actually constant-time. The cost of performing the actual swap is indeed O(1), but then there's the cost of the std::vector destructor firing and cleaning up all the allocated space. That can potentially have cost Ω(n) if the underlying objects have nontrivial destructors, since the std::vector needs to go and invoke those destructors. There's also the cost of invoking the copy constructors for all the elements stored in the initial vector, which is similarly Ω(n).

As a result, both approaches should have roughly the same complexity, except that shrink_to_fit more clearly telegraphs the intention and is probably more amenable to compiler optimizations.

like image 102
templatetypedef Avatar answered Sep 22 '22 19:09

templatetypedef


Accepted answer that also got featured on isocpp.org is wrong.

shrink_to_fit is nonbinding requirement. I personally I think it is idiotic from ISO to leave this as nonbiding(without providing some stronger guarantees about what happens) since it is confusing, but maybe they had good reasons(tm).

like image 44
NoSenseEtAl Avatar answered Sep 24 '22 19:09

NoSenseEtAl