Object pool vs. dynamic allocation

2019-02-03 10:21发布

问题:

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:

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



回答3:

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.



回答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.