Skip to content

Instantly share code, notes, and snippets.

@eriksk
Created July 29, 2012 15:56
Show Gist options
  • Save eriksk/3199757 to your computer and use it in GitHub Desktop.
Save eriksk/3199757 to your computer and use it in GitHub Desktop.
C# Resource pooling
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OGLib.Utilities
{
public class Pool<T> where T : class, new()
{
private T[] items;
private int count;
public Pool(int capacity)
{
items = new T[capacity];
for (int i = 0; i < capacity; i++)
{
items[i] = new T();
}
count = 0;
}
public int Count
{
get { return count; }
}
public T Pop()
{
return items[count++];
}
public void Push(int index)
{
T temp = items[count - 1];
items[count - 1] = items[index];
items[index] = temp;
count--;
}
public T this[int index]
{
get { return items[index]; }
}
public void Clear()
{
count = 0;
}
}
}
/**
* USAGE
*/
Pool<Entity> entities = new Pool<Entity>(1024);
// Get a new entity
Entity entity = entities.pop()
entity.Initialize();
// kill entitites
for(int i = 0; i < entities.count; i++)
{
if(!entities[i].alive){
entities.push(i--); // decrement i because we remove one
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment