diff --git a/encompass-cs/Collections/BitArrayPool.cs b/encompass-cs/Collections/BitArrayPool.cs new file mode 100644 index 0000000..0f0165f --- /dev/null +++ b/encompass-cs/Collections/BitArrayPool.cs @@ -0,0 +1,33 @@ +using System.Collections; +using System.Collections.Generic; + +namespace Encompass +{ + internal class BitArrayPool + { + private Stack bitArrays; + + public BitArrayPool(int capacity) + { + bitArrays = new Stack(capacity); + + for (var i = 0; i < capacity; i++) + { + bitArrays.Push(new BitArray(128)); + } + } + + public BitArray Obtain(int size) + { + var bitArray = bitArrays.Pop(); + bitArray.Length = size; + bitArray.SetAll(false); + return bitArray; + } + + public void Free(BitArray bitArray) + { + bitArrays.Push(bitArray); + } + } +} diff --git a/encompass-cs/Collections/ComponentStore.cs b/encompass-cs/Collections/ComponentStore.cs index f5c3b31..88c4d12 100644 --- a/encompass-cs/Collections/ComponentStore.cs +++ b/encompass-cs/Collections/ComponentStore.cs @@ -81,7 +81,7 @@ namespace Encompass { entry.Remove(entity); } - componentBitSet.DestroyEntity(entity); + componentBitSet.RemoveEntity(entity); } public bool Any() where TComponent : struct, IComponent diff --git a/encompass-cs/ComponentBitSet.cs b/encompass-cs/ComponentBitSet.cs index ea44dc4..38c0000 100644 --- a/encompass-cs/ComponentBitSet.cs +++ b/encompass-cs/ComponentBitSet.cs @@ -6,6 +6,7 @@ namespace Encompass { internal class ComponentBitSet { + BitArrayPool bitArrayPool = new BitArrayPool(32768); // todo: set entity cap Dictionary entities = new Dictionary(); Dictionary typeToIndex = new Dictionary(); BitArray queryArray; @@ -26,13 +27,17 @@ namespace Encompass public void Clear() { + foreach (var kvp in entities) + { + bitArrayPool.Free(kvp.Value); + } entities.Clear(); } public void AddEntity(Entity entity) { - var bitArray = new BitArray(typeToIndex.Count); - entities.Add(entity, bitArray); // this is gonna create garbage!! fuck!! + var bitArray = bitArrayPool.Obtain(typeToIndex.Count); + entities.Add(entity, bitArray); } public void Set(Entity entity) where TComponent : struct, IComponent @@ -46,9 +51,13 @@ namespace Encompass entities[entity].Set(typeToIndex[typeof(TComponent)], false); } - public void DestroyEntity(Entity entity) + public void RemoveEntity(Entity entity) { - entities.Remove(entity); + if (entities.ContainsKey(entity)) + { + bitArrayPool.Free(entities[entity]); + entities.Remove(entity); + } } public IEnumerable EntitiesWithComponents(IEnumerable types)