using System; using System.Collections.Generic; namespace Unity.VisualScripting { public static class DictionaryPool { private static readonly object @lock = new object(); private static readonly Stack> free = new Stack>(); private static readonly HashSet> busy = new HashSet>(); // Do not allow an IDictionary parameter here to avoid allocation on foreach public static Dictionary New(Dictionary source = null) { lock (@lock) { if (free.Count == 0) { free.Push(new Dictionary()); } var dictionary = free.Pop(); busy.Add(dictionary); if (source != null) { foreach (var kvp in source) { dictionary.Add(kvp.Key, kvp.Value); } } return dictionary; } } public static void Free(Dictionary dictionary) { lock (@lock) { if (!busy.Contains(dictionary)) { throw new ArgumentException("The dictionary to free is not in use by the pool.", nameof(dictionary)); } dictionary.Clear(); busy.Remove(dictionary); free.Push(dictionary); } } } }