| | | 1 | | using System.Runtime.CompilerServices; |
| | | 2 | | |
| | | 3 | | namespace NGql.Core.Pooling; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Lock-free pool for SortedDictionary arguments with thread-local optimization to eliminate contention |
| | | 7 | | /// </summary> |
| | | 8 | | internal static class LockFreeArgumentsPool |
| | | 9 | | { |
| | 3 | 10 | | private static readonly ThreadLocalPool<SortedDictionary<string, object?>> _pool = new( |
| | 12 | 11 | | factory: () => new SortedDictionary<string, object?>(StringComparer.OrdinalIgnoreCase), |
| | 27 | 12 | | reset: dict => dict.Clear(), |
| | 3 | 13 | | poolName: "arguments" |
| | 3 | 14 | | ); |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Gets a pooled dictionary populated from source |
| | | 18 | | /// </summary> |
| | | 19 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 20 | | internal static PooledArguments GetPooled(Dictionary<string, object?> source) |
| | | 21 | | { |
| | 27 | 22 | | var dict = _pool.Get(); |
| | 84 | 23 | | foreach (var kvp in source) |
| | 15 | 24 | | dict[kvp.Key] = kvp.Value; |
| | 27 | 25 | | return new PooledArguments(dict); |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Returns dictionary to the pool |
| | | 30 | | /// </summary> |
| | | 31 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 32 | | [System.Diagnostics.CodeAnalysis.SuppressMessage("Major Code Smell", "S3398:Move this method inside 'PooledArguments |
| | 27 | 33 | | private static void Return(SortedDictionary<string, object?> dict) => _pool.Return(dict); |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Zero-allocation ref struct wrapper with lock-free pooling |
| | | 37 | | /// </summary> |
| | | 38 | | internal readonly ref struct PooledArguments |
| | | 39 | | { |
| | | 40 | | public readonly SortedDictionary<string, object?> Dictionary; |
| | 27 | 41 | | internal PooledArguments(SortedDictionary<string, object?> dictionary) => Dictionary = dictionary; |
| | 27 | 42 | | public void Dispose() => Return(Dictionary); |
| | | 43 | | } |
| | | 44 | | } |