using System; using System.Collections.Generic; using XGame.Framework.Memory; namespace XGame.Framework { /// /// List缓存池 /// * 非线程安全 /// public static partial class ListPool { static readonly Dictionary> pool = new(); const int CACHE_LIMIT = 32; internal static void Initialize() { MemoryMonitor.Register(Clear); } internal static void Dispose() { pool.Clear(); MemoryMonitor.UnRegister(Clear); } public static void Clear() { pool.Clear(); } public static List Acquire() { Type type = typeof(T); if (pool.ContainsKey(type)) { var stack = pool[type]; if (stack.Count > 0) return stack.Pop() as List; } return new List(); } public static void Recycle(List list) { if ( list == null) { return; } Type type = typeof(T); if (!pool.TryGetValue(type, out var stack)) { stack = new Stack(); pool.Add(type, stack); } list.Clear(); if (stack.Count >= CACHE_LIMIT) stack.Clear(); else if (stack.Contains(list)) { Log.Error($"ObjectPool.Recycle 重复回收, type: {type.FullName}"); return; } stack.Push(list); } } }