using System; using System.Collections.Generic; namespace ZXL { public static class ListPool { private static readonly object @lock = new object(); private static readonly Stack> free = new Stack>(); private static readonly HashSet> busy = new HashSet>(); public static List New() { lock (@lock) { if (free.Count == 0) { free.Push(new List()); } var array = free.Pop(); busy.Add(array); return array; } } public static void Free(List list) { lock (@lock) { if (!busy.Contains(list)) { throw new ArgumentException("The list to free is not in use by the pool.", nameof(list)); } list.Clear(); busy.Remove(list); free.Push(list); } } } public static class XListPool { public static List ToListPooled(this IEnumerable source) { var list = ListPool.New(); foreach (var item in source) { list.Add(item); } return list; } public static void Free(this List list) { ListPool.Free(list); } } }