11using System . Collections . Concurrent ;
2+ using System . Threading ;
23
34namespace Wanhjor . ObjectInspector
45{
@@ -9,6 +10,7 @@ namespace Wanhjor.ObjectInspector
910 public ref struct DuckTypeLeasing < TInterface > where TInterface : class
1011 {
1112 private static readonly ConcurrentStack < TInterface > Proxies = new ConcurrentStack < TInterface > ( ) ;
13+ private static TInterface ? _firstItem ;
1214
1315 /// <summary>
1416 /// Current duck type instance
@@ -24,12 +26,20 @@ public void Dispose()
2426 var inst = Instance ;
2527 Instance = default ! ;
2628 ( ( ISettableDuckType ) inst ) . SetInstance ( null ! ) ;
29+ if ( _firstItem == null )
30+ {
31+ _firstItem = inst ;
32+ return ;
33+ }
2734 Proxies . Push ( inst ) ;
2835 }
2936
3037 internal static DuckTypeLeasing < TInterface > Rent ( IDuckTypeFactory < TInterface > factory , object instance )
3138 {
32- if ( ! Proxies . TryPop ( out var proxy ) )
39+ var proxy = _firstItem ;
40+ if ( proxy != null && proxy == Interlocked . CompareExchange ( ref _firstItem , null , proxy ) )
41+ ( ( ISettableDuckType ) proxy ) . SetInstance ( instance ) ;
42+ else if ( ! Proxies . TryPop ( out proxy ) )
3343 proxy = factory . Create ( instance ) ;
3444 else
3545 ( ( ISettableDuckType ) proxy ) . SetInstance ( instance ) ;
@@ -40,7 +50,17 @@ internal static DuckTypeLeasing<TInterface> Rent(IDuckTypeFactory<TInterface> fa
4050 }
4151 internal static DuckTypeLeasing < IDuckType > RentDuckType ( IDuckTypeFactory factory , object instance )
4252 {
43- if ( ! ( Proxies . TryPop ( out var proxy ) && proxy is ISettableDuckType dtProxy ) )
53+ var proxy = _firstItem ;
54+ if ( proxy != null && proxy == Interlocked . CompareExchange ( ref _firstItem , null , proxy ) && proxy is ISettableDuckType sProxy )
55+ {
56+ sProxy . SetInstance ( instance ) ;
57+ return new DuckTypeLeasing < IDuckType >
58+ {
59+ Instance = sProxy
60+ } ;
61+ }
62+
63+ if ( ! ( Proxies . TryPop ( out proxy ) && proxy is ISettableDuckType dtProxy ) )
4464 dtProxy = ( ISettableDuckType ) factory . Create ( instance ) ;
4565 else
4666 dtProxy . SetInstance ( instance ) ;
0 commit comments