Destroying tree structured vectors of std::unique_ptr

208 views Asked by At

I have been migrating my code to use std::unique_ptr.

When I had to decide about one class which had a tree hierarchy, I decided to let the object own their children, so that removing an object from the tree would delete it. However I have noticed that in complex hierarchies of thousands of elements destroying it is really slow. Like, unbelievably slow.

So is it simply advised not to nest vectors of unique pointers, and should I switch to a flat layout of the unique_ptr, and just keep regular pointers in the tree ? I am imagining that it may be a well known fact that this is a no-go, but it is puzzling me as I had a hard time finding literature on this specific detail.

#include <vector>
#include <memory>

class Element
{
    std::vector<std::unique_ptr<Element>> mChildren;
};

UPDATE : After a long hestitation whether or not to delete my question, I noticed my problem is quite similar to this one : fast way to delete entries of STL vector of pointers

With the addition that the process is even slower with the tree structure. unique_ptr doesn't seem to be responsible here after all.

I wrote a piece of code to investigate it

  • destroying 60 000 elements, unique_ptr, flat layout takes about 5 seconds

  • destroying 60 000 elements, unique_ptr, tree layout takes about 8 seconds

Without unique_ptr the times are only marginally lower.

So the actual problem I'm facing is just that it's slow to delete 60 000 things in a row. Then I imagine my solutions are similar the ones in the linked question :

  • Pool memory for elements that I know I'm gonna delete in batchs, but it's said to be very cumbersome and prone to grave errors

  • Have a worker thread do it, that is it will stay slow but will not hinder the main thread anymore

I'm technically unsavy as to how to properly execute both, but I suppose it will educate me.

0

There are 0 answers