Object Pooling in .NET and how to use Object Pool
How do you do object pooling in .NET:
The MTS Glossary was defines Pooling is "A performance
optimization based on using collections of pre-allocated resources, such as
objects or database connections."
Why the object pooling in asp.net:
In software development, we often face problems while our
application is under high stress. Most of the problem is due to issues in
memory management. So developers should take some extra care so that an
application will be optimized and follows proper memory management principles.
What is the Asp.net object pooling mean?
The Object Pool is
nothing it is a simple container of objects that are ready for use. Whenever
there is a request for a new object, the pool manager will take the request and
it will be served by allocating an object from the pool.
Asp.net Object Pooling Example by C#:
using System;
using System.Collections;
namespace ObjectPooling
{
class Factory
{
// Maximum objects allowed!
private static int PoolMax_Size =
2;
// My Collection Pool
private static readonly Queue objPool = new Queue(PoolMax_Size);
public Employee GetEmployee()
{
Employee objEmployee;
// here check from the collection pool. If exists return object
else create new
if (Employee.Counter >=
PoolMax_Size && objPool.Count>0)
{
// Retrieve thr object from pool
objEmployee = RetrieveFromPool();
}
else
{
objEmployee = GetNewEmployee();
}
return objEmployee;
}
private Employee GetNewEmployee()
{
// creates a new employee
Employee objEmp = new Employee();
objPool.Enqueue(objEmp);
return objEmp;
}
protected Employee RetrieveFromPool()
{
Employee objEmp;
// if there is any objects in my collection
if (objPool.Count>0)
{
objEmp = (Employee)objPool.Dequeue();
Employee.Counter--;
}
else
{
// return a new object
objEmp = new Employee();
}
return objEmp;
}
}
class Employee
{
public static int Counter = 0;
public Employee()
{
++Counter;
}
private string First_name;
public string Firstname
{
get
{
return First_name;
}
set
{
First_name = value;
}
}
}
}
How to use this object Pool code:
Factory factory = new Factory();
Employee myEmp_first = factory.GetEmployee();
Console.WriteLine("First
object");
Employee myEmp_second = factory.GetEmployee();
Console.WriteLine("Second
object")
Comments
Post a Comment