Skip to content

Commit

Permalink
DuckLeasing performance improvements and bump to 0.4.0 version
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyredondo committed Jun 23, 2020
1 parent b7c5c84 commit b19b389
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
24 changes: 22 additions & 2 deletions src/Wanhjor.ObjectInspector/DuckTypeLeasing.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Threading;

namespace Wanhjor.ObjectInspector
{
Expand All @@ -9,6 +10,7 @@ namespace Wanhjor.ObjectInspector
public ref struct DuckTypeLeasing<TInterface> where TInterface:class
{
private static readonly ConcurrentStack<TInterface> Proxies = new ConcurrentStack<TInterface>();
private static TInterface? _firstItem;

/// <summary>
/// Current duck type instance
Expand All @@ -24,12 +26,20 @@ public void Dispose()
var inst = Instance;
Instance = default!;
((ISettableDuckType) inst).SetInstance(null!);
if (_firstItem == null)
{
_firstItem = inst;
return;
}
Proxies.Push(inst);
}

internal static DuckTypeLeasing<TInterface> Rent(IDuckTypeFactory<TInterface> factory, object instance)
{
if (!Proxies.TryPop(out var proxy))
var proxy = _firstItem;
if (proxy != null && proxy == Interlocked.CompareExchange(ref _firstItem, null, proxy))
((ISettableDuckType)proxy).SetInstance(instance);
else if (!Proxies.TryPop(out proxy))
proxy = factory.Create(instance);
else
((ISettableDuckType)proxy).SetInstance(instance);
Expand All @@ -40,7 +50,17 @@ internal static DuckTypeLeasing<TInterface> Rent(IDuckTypeFactory<TInterface> fa
}
internal static DuckTypeLeasing<IDuckType> RentDuckType(IDuckTypeFactory factory, object instance)
{
if (!(Proxies.TryPop(out var proxy) && proxy is ISettableDuckType dtProxy))
var proxy = _firstItem;
if (proxy != null && proxy == Interlocked.CompareExchange(ref _firstItem, null, proxy) && proxy is ISettableDuckType sProxy)
{
sProxy.SetInstance(instance);
return new DuckTypeLeasing<IDuckType>
{
Instance = sProxy
};
}

if (!(Proxies.TryPop(out proxy) && proxy is ISettableDuckType dtProxy))
dtProxy = (ISettableDuckType) factory.Create(instance);
else
dtProxy.SetInstance(instance);
Expand Down
2 changes: 1 addition & 1 deletion src/Wanhjor.ObjectInspector/Wanhjor.ObjectInspector.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<Description>An efficient .NET object inspector/accesor to avoid reflection usage with duck typing support.</Description>
<LangVersion>8</LangVersion>
<Nullable>enable</Nullable>
<Version>0.4.0-beta.9</Version>
<Version>0.4.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Title>ObjectInspector</Title>
<Authors>Daniel Redondo</Authors>
Expand Down

0 comments on commit b19b389

Please sign in to comment.