Skip to content

Commit b19b389

Browse files
committed
DuckLeasing performance improvements and bump to 0.4.0 version
1 parent b7c5c84 commit b19b389

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/Wanhjor.ObjectInspector/DuckTypeLeasing.cs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Collections.Concurrent;
2+
using System.Threading;
23

34
namespace 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);

src/Wanhjor.ObjectInspector/Wanhjor.ObjectInspector.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<Description>An efficient .NET object inspector/accesor to avoid reflection usage with duck typing support.</Description>
77
<LangVersion>8</LangVersion>
88
<Nullable>enable</Nullable>
9-
<Version>0.4.0-beta.9</Version>
9+
<Version>0.4.0</Version>
1010
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
1111
<Title>ObjectInspector</Title>
1212
<Authors>Daniel Redondo</Authors>

0 commit comments

Comments
 (0)