对象池与动态分配
什么时候应该选择对象池而不是动态分配的对象?
我需要每秒创建和销毁数千个对象。 它本身足以决定支持对象池吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这足以决定支持对象池。
引用Boost文档
请参阅 Boost Pool 库
Yes, this is enough to decide in favor of object pool.
Quoting Boost documentation
See Boost Pool library
测量,测量,测量。 然后您就会知道,并且不必依赖猜测或指导。
另外,如果 Dirk Grunwald 的 CustomMalloc 仍然可用,请给尝试一下。 它综合了
malloc
的实现,该实现根据单个应用程序的需求进行了调整。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.销毁对象、解除分配、分配和构造的预期成本高于为新用途重新初始化的成本。
The expected cost of destructing the object, deallocation, allocation and construction is higher than the cost of reinitializing for a new use.
一般来说,如果您每秒创建和销毁数千个对象,您至少应该使用对象池。
您可以使用纯粹分配特定大小的对象的自定义分配器。 覆盖 new 并专门为您的对象预先分配堆。 使用位字段和数组相对简单。
基本上,如果对象较小,则自定义堆的内存效率更高(相对于小对象大小,堆开销相当高); 其速度更快; 它可以防止堆碎片; 而且更容易调试。
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.