Vector item remove vs ignore on iter [performance]

In previous subject, have created infinitive bidirectional cycle iteration for vector. Now I want to take some items from there as using this vector as the pool.

Doubts take items with the remove method or just ignore/skip them on iteration by appending some boolean flag in struct.

I suppose that skip option is faster for performance as does not require index rebuild in memory. But maybe takes additional CPU for trivial boolean condition check..

maybe this question pretty relative to the data types and volumes

If you don't care about changing the order of other items when you remove an item, a very efficient and common approach is to call swap_remove. This replaces the removed item with the last item in the Vec. So there is no shifting/copying of other items.

My only complaint is the name -- it should have been swap_pop.

3 Likes

If you do care about the order of the items and need the order to not change while removing elements, Vec::retain has optimizations that it can apply to only shift over the vector’s elements once, rather than N times using just repeated remove.

Whether this is better than setting a skip flag depends.
How often are you removing elements compared to iterating over the list?
retain is more expensive than setting some flags (because retain copies the other elements over), but if iteration is much more common the cost of checking the flags will become higher.
As always with anything performance-related: benchmark. If the difference between the solutions is 5 microseconds and the code runs interactively (i.e. not 100+ times per second), it doesn’t matter.

2 Likes