Created
August 19, 2017 08:00
-
-
Save audinue/484a101b42feeb32b5fe5965afba9971 to your computer and use it in GitHub Desktop.
Eager and lazy object pools.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
/// <summary> | |
/// Implements a pool of T. | |
/// </summary> | |
public interface IPool<T> | |
where T : class, new() | |
{ | |
T Use(); | |
void Release(T poolable); | |
} | |
/// <summary> | |
/// Favors runtime over startup time. | |
/// </summary> | |
public class EagerPool<T> : IPool<T> | |
where T : class, new() | |
{ | |
private readonly int capacity; | |
private readonly T[] poolables; | |
private int available; | |
public EagerPool(int capacity) | |
{ | |
this.capacity = capacity; | |
this.poolables = new T[capacity]; | |
this.available = capacity; | |
for (int i = 0; i < capacity; i++) | |
this.poolables[i] = new T(); | |
} | |
public EagerPool() | |
: this(2048) | |
{ | |
} | |
public int Capacity | |
{ | |
get | |
{ | |
return capacity; | |
} | |
} | |
public T Use() | |
{ | |
if (available == 0) | |
throw new Exception(string.Format("No '{0}' available.", typeof(T))); | |
return poolables[--available]; | |
} | |
public void Release(T poolable) | |
{ | |
if (available == capacity) | |
throw new InvalidOperationException(string.Format("Trying to release unused '{0}'.", typeof(T))); | |
poolables[available++] = poolable; | |
} | |
} | |
/// <summary> | |
/// Favors startup time over runtime. | |
/// </summary> | |
public class LazyPool<T> : IPool<T> | |
where T : class, new() | |
{ | |
private readonly int capacity; | |
private readonly T[] poolables; | |
private int available; | |
public LazyPool(int capacity) | |
{ | |
this.capacity = capacity; | |
this.poolables = new T[capacity]; | |
this.available = capacity; | |
} | |
public int Capacity | |
{ | |
get | |
{ | |
return capacity; | |
} | |
} | |
public T Use() | |
{ | |
if (available == 0) | |
throw new InvalidOperationException(string.Format("No '{0}' available.", typeof(T))); | |
var poolable = poolables[--available]; | |
if (poolable == null) | |
poolable = new T(); | |
return poolable; | |
} | |
public void Release(T poolable) | |
{ | |
if (available == capacity) | |
throw new InvalidOperationException(string.Format("Trying to release unused '{0}'.", typeof(T))); | |
poolables[available++] = poolable; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment