回收释放的对象 [英] Recycle Freed Objects
问题描述
假设我需要在堆上频繁地(任意大小)分配和删除对象,是否有任何性能优势,如果不删除这些对象,我会将其返回到一些池以后再次使用?
会减少堆分配/释放吗?或者它会比内存分配器性能慢,因为池需要管理指针的动态集合。 / p>
我的用例:假设我创建一个基于链表的队列容器,该列表的每个节点都分配在堆上,所以每次调用push()和pop ()将分配和释放该节点:
`
< typename T> struct QueueNode {
QueueNode< T> * next;
T object;
}
template< typename T> class Queue {
void push(T object){
QueueNode< T> * newNode = QueueNodePool< T> // get recycle node
if(!newNode){
newNode = new QueueNode< T>(object);
}
// push newNode routine here ..
}
T pop(){
// pop routine here ...
QueueNodePool< T> ; :: store(unusedNode); // recycle node
return unusedNode-> object;
}
}
`
池化是一种非常常见的技术,可以避免频繁的分配和释放。有些将其视为设计模式。
通常现有的实现,所以没有任何好处,重新发明轮子。
你可能想看一看问题http://stackoverflow.com/questions/1250983/object-pool-vs-dynamic-allocation
suppose I need to allocate and delete object on heap frequently (of arbitrary size), is there any performance benefit if instead of deleting those objects, I will return it back to some "pool" to be reused later?
would it give benefit by reduce heap allocation/deallocation?, or it will be slower compared to memory allocator performance, since the "pool" need to manage a dynamic collection of pointers.
my use case: suppose I create a queue container based on linked list, and each node of that list are allocated on the heap, so every call to push() and pop() will allocate and deallocate that node:
`
template <typename T> struct QueueNode {
QueueNode<T>* next;
T object;
}
template <typename T> class Queue {
void push(T object) {
QueueNode<T>* newNode = QueueNodePool<T>::get(); //get recycled node
if(!newNode) {
newNode = new QueueNode<T>(object);
}
// push newNode routine here..
}
T pop() {
//pop routine here...
QueueNodePool<T>::store(unusedNode); //recycle node
return unusedNode->object;
}
}
`
Pooling is a very common technique to avoid frequent allocations and deallocations. Some treat it as a design pattern. There are typically existing implementations, so there is no benefit to reinventing the wheel.
You may want to take a look at the question http://stackoverflow.com/questions/1250983/object-pool-vs-dynamic-allocation
这篇关于回收释放的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!