In my application, I have a module that manages some sorted sets representing part of the application's current state. They are stored in a 2d fixed-size array (i.e. std::array<std::array<std::set<MyObj, MyObjCmp>, x>, y>).
Another module uses these sets as a starting point for a simulation of how the state is expected to change over the next few minutes. During the simulation, it needs to modify the data stored in the sets. As the simulation module should not change the first module's current state, I am taking a copy of the sets before running the simulation. I'm doing the copy through simple assignment.
In profiling my simulator, I am seeing that the copying is much more expensive than I had expected. In the call stack of std::array::operator=, I am seeing calls to my set comparator function, which seems to indicate that the set copy is actually inserting all of the elements again rather than copying them directly in their current sorted order.
Is there any way to copy a std::set in a more efficient way?
Caleth's comment pointing at
flat_setlooks like the way to go for efficient copying while preserving set semantics. I'm on C++20 though so I haven't been able to test this directly.I was able to take that inspiration and refactor my code to use
std::vectoras the container, with manual calls tostd::sortas needed. Profiling shows that for my use case the copy is 10x faster and all other usages are roughly the same.