Sunday, March 15, 2009

Reuse the object using Object Pool

There are some requirement that we need to instantiate the object again and again. New object always takes some resource (in memory). Our normal practice is, create a object and dispose (it happens automatically when go out of scope) it once no longer required. It is ok if number of objects creation are not more. 

But there are some situations where we can hold the object instead of disposing it and reuse it again. 

Hence, I have created generic object pool, which tries to get the object from pool. If pool is empty it creates new and return. One can push object back to pool once no longer in use. 

Create generic object pool class
public class ObjectPool where T : class, new()
{
Stack queue;

public ObjectPool()
{
queue = new Stack();
}

public ObjectPool(int capacity)
{
queue = new Stack(capacity);
}

To pop the object from pool. It creates new object if couldn't found from pool 
public T Pop()
{
T retObj = null;
lock (queue)
{
if (queue.Count > 0)
retObj = queue.Pop();
}

if (retObj == null)
retObj = new T();
return retObj;
}

To push back the object into pool for reuse
public void Push(T obj)
{
if (obj == null) return;

lock (queue)
{
queue.Push(obj);
}
}

To get the number of objects in pool

public int Length
{
get
{ return queue.Count; }
}
}

No comments:

Post a Comment