add some basic object pooling support

This commit is contained in:
Gered 2013-08-22 10:13:41 -04:00
parent b22d442343
commit 4d49304ec4
4 changed files with 97 additions and 0 deletions

View file

@ -137,6 +137,9 @@
<Compile Include="Support\StringBuilderExtensions.cs" /> <Compile Include="Support\StringBuilderExtensions.cs" />
<Compile Include="Graphics\Helpers\GraphicsHelpers.cs" /> <Compile Include="Graphics\Helpers\GraphicsHelpers.cs" />
<Compile Include="Support\BitExtensions.cs" /> <Compile Include="Support\BitExtensions.cs" />
<Compile Include="Support\ObjectPool.cs" />
<Compile Include="Support\IPoolable.cs" />
<Compile Include="Support\BasicObjectPool.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<ItemGroup> <ItemGroup>

View file

@ -0,0 +1,23 @@
using System;
namespace Blarg.GameFramework.Support
{
public class BasicObjectPool<T> : ObjectPool<T> where T : class, new()
{
public BasicObjectPool()
: base()
{
}
public BasicObjectPool(int initialCapacity)
: base(initialCapacity)
{
}
protected override T Allocate()
{
return new T();
}
}
}

View file

@ -0,0 +1,10 @@
using System;
namespace Blarg.GameFramework.Support
{
public interface IPoolable
{
void Reset();
}
}

View file

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
namespace Blarg.GameFramework.Support
{
public abstract class ObjectPool<T> where T : class
{
List<T> _objects;
int _objectCount;
public ObjectPool()
: this(16)
{
}
public ObjectPool(int initialCapacity)
{
_objects = new List<T>(initialCapacity);
_objectCount = 0;
}
protected abstract T Allocate();
public T Take()
{
if (_objectCount == 0)
return Allocate();
else
{
// remove the last object in the list
int index = _objectCount - 1;
T obj = _objects[index];
// shrink the object list
_objects[index] = null;
--_objectCount;
return obj;
}
}
public void Free(T obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
int index = _objectCount;
if (index >= _objects.Count)
// need to grow the object list by one
_objects.Add(obj);
else
_objects[index] = obj;
++_objectCount;
if (obj is IPoolable)
((IPoolable)obj).Reset();
}
}
}