fast way to delete entries of STL vector of pointers

你离开我真会死。 提交于 2019-12-06 03:31:14

One thing you may be looking for is a custom allocator for the classes you allocate - this way you can effectively get and release memory to the system in bulk rather then in tiny fragments - it's probably the only solution for improving "overall" performance of this system without modifying it (which given your bottleneck sure looks like a good idea ;) ).

Any correct solution is going to boil down to doing a delete on each pointer. Since you have profiled your code and identified that as being the bottleneck, then I would look for a solution that moves the delete to another thread.

This could be done by:

  1. Create a worker thread that deletes pointers passed in
  2. Remove the pointers from the vector and copy them to another vector, owned by the worker thread
  3. Kick off the worker thread job, let it delete the pointers

This isn't going to be any faster than your current solution in terms of pure CPU time (and in fact can be slower depending on how you do it), but it will move the heavy lifting out of your main thread.

Another method that might improve performance is to use a kind of memory pool, in which you allocate one big raw buffer up front, and then placement-new each individual object within that buffer.

This has the potential of improving performance because, although you still have to destroy each pointer, that destruction is done via calling the destructor directly rather than deleteing it. This avoids having to go down to the system's memory manager, and that avoidance is where the potential lies for performance improvements.

There are significant caveats to this approach however, and I wouldn't recommend it in any but the most extreme cases. Among the caveats is the onerous responsibility you place on yourself to manage your own memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!