考虑用于从其他线程传输计算结果的大量堆分配对象。销毁这些可能是一项昂贵的任务。
我处于不再需要这些对象的情况下,我只是希望它们垃圾收集而不会阻塞主线程。我考虑使用std::async
以下方式异步销毁它们:
#include <memory>
#include <future>
#include <vector>
struct Foo
{
// Complex structure containing heap allocated data.
};
void f() {
std::vector<std::unique_ptr<Foo>> graveyard;
// Process some foo and add them in graveyard.
std::async([fooMoved = std::move(graveyard)]{});
}
在我正在使用的特定程序中,使用Visual Studio,分析似乎确认这是更快 - 至少相对于主线程 - 而不仅仅是让graveyard破坏其内容f
范围结束。
这种改进是否是我测试条件特有的故障,还是解除大量堆数据的可靠方法?你看到任何潜在的缺点吗?是否有更好的方法来执行类似的任务?