namespace NRKernal { using System; using System.Collections.Generic; using UnityEngine; /// An object pool. public class ObjectPool { /// Dictionary of cache pools. private Dictionary> m_CachePoolDict = new Dictionary>(); /// Number of initializes. public int InitCount = 100; /// Expansions this object. /// Generic type parameter. public void Expansion() where T : new() { var queue = GetQueue(); for (int i = 0; i < InitCount; i++) { T data = new T(); queue.Enqueue(data); } } /// Gets the get. /// Generic type parameter. /// A T. public T Get() where T : new() { var queue = GetQueue(); if (queue.Count == 0) { Expansion(); } return (T)queue.Dequeue(); } /// Puts the given data. /// Generic type parameter. /// The data. public void Put(T data) where T : new() { var queue = GetQueue(); queue.Enqueue(data); } /// Gets the queue. /// Generic type parameter. /// The queue. private Queue GetQueue() where T : new() { Queue queue = null; m_CachePoolDict.TryGetValue(typeof(T), out queue); if (queue == null) { queue = new Queue(); m_CachePoolDict.Add(typeof(T), queue); } return queue; } public void Clear() { m_CachePoolDict.Clear(); } } /// The bytes pool. public class BytesPool { /// Dictionary of bytes. public Dictionary> BytesDict = new Dictionary>(); /// Gets a byte[] using the given length. /// The Length to get. /// A byte[]. public byte[] Get(int len) { if (len <= 0) { NRDebugger.Info("BytesPool get len is not valid :" + len); return null; } Queue que = null; BytesDict.TryGetValue(len, out que); if (que == null) { que = new Queue(); byte[] temp = new byte[len]; que.Enqueue(temp); BytesDict.Add(len, que); } else if (que.Count == 0) { byte[] temp = new byte[len]; que.Enqueue(temp); } return que.Dequeue(); } /// Puts the given data. /// The data to put. public void Put(byte[] data) { if (data == null || data.Length == 0) { NRDebugger.Info("BytesPool retrieve data is null."); return; } Queue que = null; BytesDict.TryGetValue(data.Length, out que); if (que == null) { que = new Queue(); BytesDict.Add(data.Length, que); } que.Enqueue(data); } public void Clear() { BytesDict.Clear(); } } }