Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance / allocations of RegisterAs* methods #45

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions BoDi.Performance.Tests/Benchmarks/RegisterInstance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using BenchmarkDotNet.Attributes;

namespace BODi.Performance.Tests.Benchmarks
{
public class RegisterInstance : SingleEmptyContainerBenchmarkBase
{
private readonly TypeRegistered instance = new TypeRegistered();

[Benchmark(Baseline = true, Description = "v1.4")]
public void Version_1_4()
{
Container14.RegisterInstanceAs(instance);
}

[Benchmark(Description = "v1.BoDi_Concurrent_Dictionary_And_Lazy")]
public void Version_1_BoDi_Concurrent_Dictionary_And_Lazy()
{
Container1Concurrent_Dictionary_And_Lazy.RegisterInstanceAs(instance);
}

[Benchmark(Description = "Current")]
public void CurrentVersion()
{
ContainerCurrent.RegisterInstanceAs(instance);
}
}
}
25 changes: 25 additions & 0 deletions BoDi.Performance.Tests/Benchmarks/RegisterTypeAs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using BenchmarkDotNet.Attributes;

namespace BODi.Performance.Tests.Benchmarks
{
public class RegisterTypeAs : SingleEmptyContainerBenchmarkBase
{
[Benchmark(Baseline = true, Description = "v1.4")]
public void Version_1_4()
{
Container14.RegisterTypeAs<TypeRegistered, TypeRegistered>();
}

[Benchmark(Description = "v1.BoDi_Concurrent_Dictionary_And_Lazy")]
public void Version_1_BoDi_Concurrent_Dictionary_And_Lazy()
{
Container1Concurrent_Dictionary_And_Lazy.RegisterTypeAs<TypeRegistered, TypeRegistered>();
}

[Benchmark(Description = "Current")]
public void CurrentVersion()
{
ContainerCurrent.RegisterTypeAs<TypeRegistered, TypeRegistered>();
}
}
}
25 changes: 25 additions & 0 deletions BoDi.Performance.Tests/Benchmarks/RegisterTypeAsName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using BenchmarkDotNet.Attributes;

namespace BODi.Performance.Tests.Benchmarks
{
public class RegisterTypeAsName : SingleEmptyContainerBenchmarkBase
{
[Benchmark(Baseline = true, Description = "v1.4")]
public void Version_1_4()
{
Container14.RegisterTypeAs<TypeRegistered, TypeRegistered>("Name");
}

[Benchmark(Description = "v1.BoDi_Concurrent_Dictionary_And_Lazy")]
public void Version_1_BoDi_Concurrent_Dictionary_And_Lazy()
{
Container1Concurrent_Dictionary_And_Lazy.RegisterTypeAs<TypeRegistered, TypeRegistered>("Name");
}

[Benchmark(Description = "Current")]
public void CurrentVersion()
{
ContainerCurrent.RegisterTypeAs<TypeRegistered, TypeRegistered>("Name");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
using BoDi;

namespace BODi.Performance.Tests.Benchmarks
{
[HtmlExporter]
[MarkdownExporterAttribute.GitHub]
[MemoryDiagnoser]
[MinColumn, MaxColumn, MeanColumn, MedianColumn, RankColumn]
[Orderer(SummaryOrderPolicy.FastestToSlowest, MethodOrderPolicy.Declared)]
public abstract class SingleEmptyContainerBenchmarkBase
{
protected internal ObjectContainer ContainerCurrent;
protected internal BoDi1_4.ObjectContainer Container14;
protected internal BoDi_Concurrent_Dictionary_And_Lazy.ObjectContainer Container1Concurrent_Dictionary_And_Lazy;

[GlobalSetup]
public void Setup()
{
Container14 = new BoDi1_4.ObjectContainer();
Container1Concurrent_Dictionary_And_Lazy = new BoDi_Concurrent_Dictionary_And_Lazy.ObjectContainer();
ContainerCurrent = new ObjectContainer();
}

protected internal class FactoryRegistered { }

protected internal class TypeRegistered { }

protected internal interface IAllRegisteredFromType { }

protected internal interface IAllRegisteredFromFactory { }

private class AllRegistered1 : IAllRegisteredFromType, IAllRegisteredFromFactory {}
private class AllRegistered2 : IAllRegisteredFromType, IAllRegisteredFromFactory {}
private class AllRegistered3 : IAllRegisteredFromType, IAllRegisteredFromFactory {}
private class AllRegistered4 : IAllRegisteredFromType, IAllRegisteredFromFactory {}
}
}
103 changes: 42 additions & 61 deletions BoDi/BoDi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;

Expand Down Expand Up @@ -542,6 +543,10 @@ public NonDisposableWrapper(object obj)

private class NamedInstanceDictionaryRegistration : IRegistration
{
public static NamedInstanceDictionaryRegistration Instance = new NamedInstanceDictionaryRegistration();

private NamedInstanceDictionaryRegistration() { }

public object Resolve(ObjectContainer container, RegistrationKey keyToResolve, ResolutionList resolutionPath)
{
var typeToResolve = keyToResolve.Type;
Expand Down Expand Up @@ -606,15 +611,12 @@ public ObjectContainer(IObjectContainer baseContainer = null)

public IStrategyRegistration RegisterTypeAs<TInterface>(Type implementationType, string name = null) where TInterface : class
{
Type interfaceType = typeof(TInterface);
return RegisterTypeAs(implementationType, interfaceType, name);
return RegisterTypeAs(implementationType, typeof(TInterface), name);
}

public IStrategyRegistration RegisterTypeAs<TType, TInterface>(string name = null) where TType : class, TInterface
{
Type interfaceType = typeof(TInterface);
Type implementationType = typeof(TType);
return RegisterTypeAs(implementationType, interfaceType, name);
return RegisterTypeAs(typeof(TType), typeof(TInterface), name);
}

public IStrategyRegistration RegisterTypeAs(Type implementationType, Type interfaceType)
Expand All @@ -624,7 +626,7 @@ public IStrategyRegistration RegisterTypeAs(Type implementationType, Type interf
return RegisterTypeAs(implementationType, interfaceType, null);
}

private bool IsValidTypeMapping(Type implementationType, Type interfaceType)
private static bool IsValidTypeMapping(Type implementationType, Type interfaceType)
{
if (interfaceType.IsAssignableFrom(implementationType))
return true;
Expand All @@ -648,19 +650,6 @@ private static IEnumerable<Type> GetBaseTypes(Type type)
.Concat(GetBaseTypes(type.BaseType));
}


private RegistrationKey CreateNamedInstanceDictionaryKey(Type targetType)
{
return new RegistrationKey(typeof(IDictionary<,>).MakeGenericType(typeof(string), targetType), null);
}

private void AddRegistration(RegistrationKey key, IRegistration registration)
{
registrations[key] = registration;

AddNamedDictionaryRegistration(key);
}

private IRegistration EnsureImplicitRegistration(RegistrationKey key)
{
var registration = registrations.GetOrAdd(key, (registrationKey => new TypeRegistration(registrationKey.Type)));
Expand All @@ -670,47 +659,58 @@ private IRegistration EnsureImplicitRegistration(RegistrationKey key)
return registration;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AddNamedDictionaryRegistration(RegistrationKey key)
{
if (key.Name != null)
{
var dictKey = CreateNamedInstanceDictionaryKey(key.Type);
registrations.TryAdd(dictKey, new NamedInstanceDictionaryRegistration());
registrations.TryAdd(dictKey, NamedInstanceDictionaryRegistration.Instance);
}
}

private IStrategyRegistration RegisterTypeAs(Type implementationType, Type interfaceType, string name)
private static RegistrationKey CreateNamedInstanceDictionaryKey(Type targetType)
{
var registrationKey = new RegistrationKey(interfaceType, name);
AssertNotResolved(registrationKey);
return new RegistrationKey(typeof(IDictionary<,>).MakeGenericType(typeof(string), targetType), null);
}

ClearRegistrations(registrationKey);
private IStrategyRegistration RegisterTypeAs(Type implementationType, Type interfaceType, string name)
{
var typeRegistration = new TypeRegistration(implementationType);
AddRegistration(registrationKey, typeRegistration);

AddRegistration(interfaceType, name, typeRegistration);
return typeRegistration;
}

private void AddRegistration(Type interfaceType, string name, IRegistration registration)
{
var key = new RegistrationKey(interfaceType, name);
if (resolvedKeys.Contains(key))
{
throw new ObjectContainerException("An object has been resolved for this interface already.", null);
}

registrations[key] = registration;
AddNamedDictionaryRegistration(key);
}

public void RegisterInstanceAs<TInterface>(TInterface instance, string name = null, bool dispose = false) where TInterface : class
{
RegisterInstanceAs(instance, typeof(TInterface), name, dispose);
}

public void RegisterInstanceAs(object instance, Type interfaceType, string name = null, bool dispose = false)
{
if (instance == null)
throw new ArgumentNullException("instance");
var registrationKey = new RegistrationKey(interfaceType, name);
AssertNotResolved(registrationKey);
throw new ArgumentNullException(nameof(instance));

AddRegistration(interfaceType, name, new InstanceRegistration(instance));

ClearRegistrations(registrationKey);
AddRegistration(registrationKey, new InstanceRegistration(instance));
objectPool[new RegistrationKey(instance.GetType(), name)] = GetPoolableInstance(instance, dispose);
}

private static object GetPoolableInstance(object instance, bool dispose)
{
return (instance is IDisposable) && !dispose ? new NonDisposableWrapper(instance) : instance;
}

public void RegisterInstanceAs<TInterface>(TInterface instance, string name = null, bool dispose = false) where TInterface : class
{
RegisterInstanceAs(instance, typeof(TInterface), name, dispose);
return !dispose && instance is IDisposable ? new NonDisposableWrapper(instance) : instance;
}

public IStrategyRegistration RegisterFactoryAs<TInterface>(Func<TInterface> factoryDelegate, string name = null)
Expand All @@ -730,16 +730,11 @@ public void RegisterFactoryAs<TInterface>(Delegate factoryDelegate, string name

public IStrategyRegistration RegisterFactoryAs(Delegate factoryDelegate, Type interfaceType, string name = null)
{
if (factoryDelegate == null) throw new ArgumentNullException("factoryDelegate");
if (interfaceType == null) throw new ArgumentNullException("interfaceType");
if (factoryDelegate == null) throw new ArgumentNullException(nameof(factoryDelegate));
if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType));

var registrationKey = new RegistrationKey(interfaceType, name);
AssertNotResolved(registrationKey);

ClearRegistrations(registrationKey);
var factoryRegistration = new FactoryRegistration(factoryDelegate);
AddRegistration(registrationKey, factoryRegistration);

AddRegistration(interfaceType, name, factoryRegistration);
return factoryRegistration;
}

Expand All @@ -750,25 +745,11 @@ public bool IsRegistered<T>()

public bool IsRegistered<T>(string name)
{
Type typeToResolve = typeof(T);

var keyToResolve = new RegistrationKey(typeToResolve, name);
var keyToResolve = new RegistrationKey(typeof(T), name);

return registrations.ContainsKey(keyToResolve);
}

// ReSharper disable once UnusedParameter.Local
private void AssertNotResolved(RegistrationKey interfaceType)
{
if (resolvedKeys.Contains(interfaceType))
throw new ObjectContainerException("An object has been resolved for this interface already.", null);
}

private void ClearRegistrations(RegistrationKey registrationKey)
{
registrations.TryRemove(registrationKey, out IRegistration result);
}

#if !BODI_LIMITEDRUNTIME && !BODI_DISABLECONFIGFILESUPPORT
public void RegisterFromConfiguration()
{
Expand Down Expand Up @@ -863,7 +844,7 @@ private object Resolve(Type typeToResolve, ResolutionList resolutionPath, string
// if there was no named registration, we still return an empty dictionary
if (IsDefaultNamedInstanceDictionaryKey(keyToResolve))
{
return new KeyValuePair<ObjectContainer, IRegistration>(this, new NamedInstanceDictionaryRegistration());
return new KeyValuePair<ObjectContainer, IRegistration>(this, NamedInstanceDictionaryRegistration.Instance);
}

return null;
Expand Down