Nick
Nick

Reputation: 10539

Call vector destructor or clear in a different thread

I have huge vector of unique_ptr .

When I need to do clear() or call destructor it took 4-5 seconds.

One theoretical way to speed it up is to create temp vector, swap it with the huge vector I work, then start a thread and call clear on temp vector.

When looking over internet i do not see anyone speaking for optimization like this.

Is there a flaw In my optimization?

Upvotes: 2

Views: 359

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

I guess your idea should work. For example, if you have a std::vector of some data called X:

struct X
{
    // some data here
};

using DataStorage = std::vector<std::unique_ptr<X>>;

you might use std::async to move DataStorage object and call clear() on this object asynchronously:

DataStorage data;

// data usage

auto clear_task = std::async(std::launch::async,
    &DataStorage::clear, std::move(data));

// do some stuff here; data object is not used anymore

clear_task.wait();

There are no unnecessary copying here: you just move data and specify that you want to call clear() in a separate thread so that the main thread does not hang while clear operation is performed.

Upvotes: 1

Related Questions