Created
June 15, 2025 17:33
-
-
Save AsyncOperator/3d2fdc92b3c4b6aefff868a7730b64fd to your computer and use it in GitHub Desktop.
Utility structs for scoped usage of pooled List<T>, HashSet<T>, and Dictionary<TKey, TValue> in Unity. Automatically releases the collection back to the pool on disposal, enabling efficient memory reuse with using statements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public readonly struct ListPoolScope<T> : IDisposable | |
{ | |
public readonly List<T> list; | |
private ListPoolScope(List<T> list) | |
{ | |
this.list = list; | |
} | |
public static ListPoolScope<T> Rent() | |
{ | |
return new ListPoolScope<T>(ListPool<T>.Get()); | |
} | |
public void Dispose() | |
{ | |
ListPool<T>.Release(list); | |
} | |
} | |
public readonly struct HashSetPoolScope<T> : IDisposable | |
{ | |
public readonly HashSet<T> hashSet; | |
private HashSetPoolScope(HashSet<T> hashSet) | |
{ | |
this.hashSet = hashSet; | |
} | |
public static HashSetPoolScope<T> Rent() | |
{ | |
return new HashSetPoolScope<T>(HashSetPool<T>.Get()); | |
} | |
public void Dispose() | |
{ | |
HashSetPool<T>.Release(hashSet); | |
} | |
} | |
public readonly struct DictionaryPoolScope<TKey, TValue> : IDisposable | |
{ | |
public readonly Dictionary<TKey, TValue> dictionary; | |
private DictionaryPoolScope(Dictionary<TKey, TValue> dictionary) | |
{ | |
this.dictionary = dictionary; | |
} | |
public static DictionaryPoolScope<TKey, TValue> Rent() | |
{ | |
return new DictionaryPoolScope<TKey, TValue>(DictionaryPool<TKey, TValue>.Get()); | |
} | |
public void Dispose() | |
{ | |
DictionaryPool<TKey, TValue>.Release(dictionary); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment