| | | 1 | | using System.Runtime.CompilerServices; |
| | | 2 | | |
| | | 3 | | namespace NGql.Core.Pooling; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Lock-free pool for HashSet<string> instances with thread-local optimization |
| | | 7 | | /// </summary> |
| | | 8 | | internal static class LockFreeHashSetPool |
| | | 9 | | { |
| | | 10 | | private const int MaxSize = 128; // Prevent memory bloat from large sets |
| | | 11 | | private const int MaxCapacity = 256; |
| | | 12 | | |
| | 3 | 13 | | private static readonly ThreadLocalPool<HashSet<string>> _pool = new( |
| | 25 | 14 | | factory: () => new HashSet<string>(StringComparer.OrdinalIgnoreCase), |
| | 48 | 15 | | reset: set => set.Clear(), |
| | 57 | 16 | | validateForReturn: set => set.Count <= MaxSize && set.EnsureCapacity(0) <= MaxCapacity, |
| | 3 | 17 | | poolName: "hashset" |
| | 3 | 18 | | ); |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Gets an empty pooled HashSet (for warmup/testing) |
| | | 22 | | /// </summary> |
| | | 23 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 57 | 24 | | internal static PooledHashSet GetPooled() => new(_pool.Get()); |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Returns HashSet to the pool |
| | | 28 | | /// </summary> |
| | | 29 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 30 | | [System.Diagnostics.CodeAnalysis.SuppressMessage("Major Code Smell", "S3398:Move this method inside 'PooledHashSet'" |
| | 57 | 31 | | private static void Return(HashSet<string> set) => _pool.Return(set); |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Zero-allocation ref struct wrapper with lock-free pooling |
| | | 35 | | /// </summary> |
| | | 36 | | internal readonly ref struct PooledHashSet |
| | | 37 | | { |
| | | 38 | | public readonly HashSet<string> Set; |
| | 57 | 39 | | internal PooledHashSet(HashSet<string> set) => Set = set; |
| | 57 | 40 | | public void Dispose() => Return(Set); |
| | | 41 | | } |
| | | 42 | | } |