- Home /
Question by
gumboots · Nov 25, 2016 at 04:10 AM ·
listpoolinggarbage-collectionstack
Object Pooling for Class Pattern
Hi all,
I have a class that I am spawning and deleting quite often, and feel it's a smart move to pool it. Is there any reason to not use Stack as opposed to List? Can you see any potential errors here? (Outside of an object that calls Destroy() not removing its reference.)
Thanks!
public class GridCellData {
// Pooled storage of spawned but no longer used GridCellDatas
static Stack<GridCellData> pool = new Stack<GridCellData>();
public void Destroy() {
pool.Push(this);
}
public static GridCellData New() {
if (pool.Count > 0) {
return pool.Pop();
} else {
return new GridCellData();
}
}
}
Comment