Object pool vs. dynamic allocation

拥有回忆 提交于 2019-12-03 19:07:27

问题


When should one prefer object pool over dynamically allocated objects?

I need to create and destroy thousands of objects per second. Is it by itself enough to decide in favor of object pool?

Thanks.


回答1:


Yes, this is enough to decide in favor of object pool.

Quoting Boost documentation

When should I use Pool?

Pools are generally used when there is a lot of allocation and deallocation of small objects. Another common usage is the situation above, where many objects may be dropped out of memory.

See Boost Pool library




回答2:


Measure, measure, measure. Then you'll know, and you won't have to rely on speculation or guidelines.

Also, if Dirk Grunwald's CustomMalloc is still available, give it a try. It synthesizes an implementation of malloc that is tuned to the needs of a single application.




回答3:


The expected cost of destructing the object, deallocation, allocation and construction is higher than the cost of reinitializing for a new use.




回答4:


Generally if you're creating and destroying thousands of objects a second you should at least use an object pool.

You could use a custom allocator which purely allocates objects of a specific size. Override new and pre allocate a heap specifically for your objects. Using a bit field and an array its relatively simple.

Basically a custom heap is more memory efficient if the objects are small (the heap overhead is quite high relative to small objects size); Its faster; It prevents heap fragmentation; And its easier to debug.



来源:https://stackoverflow.com/questions/1250983/object-pool-vs-dynamic-allocation

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