Skip to content

Apply .NET8 MethodInvoker/ConstructorInvoker optimization #359

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

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 6 additions & 5 deletions Extensions/Xtensive.Orm.BulkOperations/Internals/Operation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,12 @@ protected void EnsureTransactionIsStarted()

public QueryTranslationResult GetRequest(IQueryable<T> query) => QueryBuilder.TranslateQuery(query);

public QueryTranslationResult GetRequest(Type type, IQueryable query)
{
var translateQueryMethod = WellKnownMembers.TranslateQueryMethod.CachedMakeGenericMethod(type);
return (QueryTranslationResult) translateQueryMethod.Invoke(QueryBuilder, new object[] {query});
}
public QueryTranslationResult GetRequest(Type type, IQueryable query) =>
#if NET8_0_OR_GREATER
(QueryTranslationResult) WellKnownMembers.TranslateQueryMethod.CachedMakeGenericMethodInvoker(type).Invoke(QueryBuilder, query);
#else
(QueryTranslationResult) WellKnownMembers.TranslateQueryMethod.CachedMakeGenericMethod(type).Invoke(QueryBuilder, new object[] {query});
#endif

public TypeInfo GetTypeInfo(Type entityType) =>
Session.Domain.Model.Hierarchies.SelectMany(a => a.Types).Single(a => a.UnderlyingType == entityType);
Expand Down
45 changes: 36 additions & 9 deletions Orm/Xtensive.Orm/IoC/ServiceContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,35 @@ public class ServiceContainer : ServiceContainerBase
{
private static readonly Type iServiceContainerType = typeof(IServiceContainer);

#if NET8_0_OR_GREATER
private static readonly Func<ServiceRegistration, Pair<ConstructorInvoker, ParameterInfo[]>> ConstructorFactory = serviceInfo => {
#else
private static readonly Func<ServiceRegistration, Pair<ConstructorInfo, ParameterInfo[]>> ConstructorFactory = serviceInfo => {
#endif
var mappedType = serviceInfo.MappedType;
var ctor = (
from c in mappedType.GetConstructors()
where c.GetAttribute<ServiceConstructorAttribute>(AttributeSearchOptions.InheritNone) != null
select c
).SingleOrDefault() ?? mappedType.GetConstructor(Array.Empty<Type>());
var @params = ctor?.GetParameters();
return new Pair<ConstructorInfo, ParameterInfo[]>(ctor, @params);
#if NET8_0_OR_GREATER
return new(ctor is null ? null : ConstructorInvoker.Create(ctor), @params);
#else
return new(ctor, @params);
#endif
};

private readonly IReadOnlyDictionary<Key, List<ServiceRegistration>> types;

private readonly ConcurrentDictionary<ServiceRegistration, Lazy<object>> instances =
new ConcurrentDictionary<ServiceRegistration, Lazy<object>>();

private readonly ConcurrentDictionary<ServiceRegistration, Pair<ConstructorInfo, ParameterInfo[]>> constructorCache =
new ConcurrentDictionary<ServiceRegistration, Pair<ConstructorInfo, ParameterInfo[]>>();
#if NET8_0_OR_GREATER
private readonly ConcurrentDictionary<ServiceRegistration, Pair<ConstructorInvoker, ParameterInfo[]>> constructorCache = new();
#else
private readonly ConcurrentDictionary<ServiceRegistration, Pair<ConstructorInfo, ParameterInfo[]>> constructorCache = new();
#endif

private readonly ConcurrentDictionary<(Type, int), bool> creating = new ConcurrentDictionary<(Type, int), bool>();

Expand Down Expand Up @@ -85,17 +96,18 @@ protected virtual object CreateInstance(ServiceRegistration serviceInfo)
return null;
}
var pInfos = cachedInfo.Second;
if (pInfos.Length == 0) {
var nArg = pInfos.Length;
if (nArg == 0) {
return Activator.CreateInstance(serviceInfo.MappedType);
}
var managedThreadId = Environment.CurrentManagedThreadId;
var key = (serviceInfo.Type, managedThreadId);
if (!creating.TryAdd(key, true)) {
throw new ActivationException(Strings.ExRecursiveConstructorParameterDependencyIsDetected);
}
var args = new object[pInfos.Length];
var args = new object[nArg];
try {
for (var i = 0; i < pInfos.Length; i++) {
for (var i = 0; i < nArg; i++) {
var type = pInfos[i].ParameterType;
if (creating.ContainsKey((type, managedThreadId))) {
throw new ActivationException(Strings.ExRecursiveConstructorParameterDependencyIsDetected);
Expand All @@ -106,10 +118,14 @@ protected virtual object CreateInstance(ServiceRegistration serviceInfo)
finally {
_ = creating.TryRemove(key, out _);
}
#if NET8_0_OR_GREATER
return cInfo.Invoke(new Span<object>(args));
#else
return cInfo.Invoke(args);
#endif
}

#endregion
#endregion

#region Private \ internal methods

Expand Down Expand Up @@ -194,17 +210,28 @@ public static IServiceContainer Create(Type containerType, object configuration,
Type configurationType = configuration?.GetType(),
parentType = parent?.GetType();
return (IServiceContainer) (
#if NET8_0_OR_GREATER
FindConstructorInvoker(containerType, configurationType, parentType)?.Invoke(configuration, parent)
?? FindConstructorInvoker(containerType, configurationType)?.Invoke(configuration)
?? FindConstructorInvoker(containerType, parentType)?.Invoke(parent)
#else
FindConstructor(containerType, configurationType, parentType)?.Invoke(new[] { configuration, parent })
?? FindConstructor(containerType, configurationType)?.Invoke(new[] { configuration })
?? FindConstructor(containerType, parentType)?.Invoke(new[] { parent })
#endif
?? throw new ArgumentException(Strings.ExContainerTypeDoesNotProvideASuitableConstructor, "containerType")
);
}

#if NET8_0_OR_GREATER
private static ConstructorInvoker FindConstructorInvoker(Type containerType, params Type[] argumentTypes) =>
containerType.GetSingleConstructorInvokerOrDefault(argumentTypes);
#else
private static ConstructorInfo FindConstructor(Type containerType, params Type[] argumentTypes) =>
containerType.GetSingleConstructorOrDefault(argumentTypes);
#endif

#endregion
#endregion

/// <summary>
/// Creates <see cref="IServiceContainer"/> by default configuration.
Expand Down Expand Up @@ -324,4 +351,4 @@ public override void Dispose()
}
}
}
}
}
8 changes: 5 additions & 3 deletions Orm/Xtensive.Orm/Modelling/PropertyAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,11 @@ private void Initialize()
dependencyRootType = pa.DependencyRootType;
compareCaseInsensitive = tProperty == WellKnownTypes.String && pa.CaseInsensitiveComparison;
}
InnerInitializeMethodDefinition
.CachedMakeGenericMethod(tType, tProperty)
.Invoke(this, null);
#if NET8_0_OR_GREATER
InnerInitializeMethodDefinition.CachedMakeGenericMethodInvoker(tType, tProperty).Invoke(this);
#else
InnerInitializeMethodDefinition.CachedMakeGenericMethod(tType, tProperty).Invoke(this, null);
#endif
}

private void InnerInitialize<TType, TProperty>()
Expand Down
10 changes: 7 additions & 3 deletions Orm/Xtensive.Orm/Orm/Linq/QueryProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,14 @@ object IQueryProvider.Execute(Expression expression)
{
var resultType = expression.Type;
var executeMethod = resultType.IsOfGenericInterface(WellKnownInterfaces.EnumerableOfT)
? WellKnownMembers.QueryProvider.ExecuteSequence.CachedMakeGenericMethod(SequenceHelper.GetElementType(resultType))
: WellKnownMembers.QueryProvider.ExecuteScalar.CachedMakeGenericMethod(resultType);
? WellKnownMembers.QueryProvider.ExecuteSequence.CachedMakeGenericMethodInvoker(SequenceHelper.GetElementType(resultType))
: WellKnownMembers.QueryProvider.ExecuteScalar.CachedMakeGenericMethodInvoker(resultType);
try {
return executeMethod.Invoke(this, new object[] {expression});
#if NET8_0_OR_GREATER
return executeMethod.Invoke(this, expression);
#else
return executeMethod.Invoke(this, new object[] { expression });
#endif
}
catch (TargetInvocationException e) {
if (e.InnerException != null) {
Expand Down
4 changes: 4 additions & 0 deletions Orm/Xtensive.Orm/Orm/Providers/StorageDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,11 @@ private static IReadOnlyCollection<IDbConnectionAccessor> CreateConnectionAccess
throw new NotSupportedException(string.Format(Strings.ExConnectionAccessorXHasNoParameterlessConstructor, type));
}

#if NET8_0_OR_GREATER
var accessorFactory = (Func<IDbConnectionAccessor>) FactoryCreatorMethod.CachedMakeGenericMethodInvoker(type).Invoke(null);
#else
var accessorFactory = (Func<IDbConnectionAccessor>) FactoryCreatorMethod.CachedMakeGenericMethod(type).Invoke(null, null);
#endif
instances.Add(accessorFactory());
factoriesLocal[type] = accessorFactory;
}
Expand Down
44 changes: 44 additions & 0 deletions Orm/Xtensive.Orm/Reflection/TypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,11 @@ public int GetHashCode((Type, Type[]) obj)
private static readonly Type CompilerGeneratedAttributeType = typeof(CompilerGeneratedAttribute);
private static readonly string TypeHelperNamespace = typeof(TypeHelper).Namespace;

#if NET8_0_OR_GREATER
private static readonly ConcurrentDictionary<(Type, Type[]), ConstructorInvoker> ConstructorInfoByTypes =
#else
private static readonly ConcurrentDictionary<(Type, Type[]), ConstructorInfo> ConstructorInfoByTypes =
#endif
new(new TypesEqualityComparer());

private static readonly ConcurrentDictionary<Type, Type[]> OrderedInterfaces = new();
Expand All @@ -68,6 +72,17 @@ public int GetHashCode((Type, Type[]) obj)

private static readonly ConcurrentDictionary<(MethodInfo, Type, Type), MethodInfo> GenericMethodInstances2 = new();

#if NET8_0_OR_GREATER
private static readonly ConcurrentDictionary<(MethodInfo, Type), MethodInvoker> GenericMethodInvokers1 = new();
private static readonly ConcurrentDictionary<(MethodInfo, Type, Type), MethodInvoker> GenericMethodInvokers2 = new();

private static readonly Func<(MethodInfo genericDefinition, Type typeArgument), MethodInvoker> GenericMethodInvokerFactory1 =
key => MethodInvoker.Create(key.genericDefinition.MakeGenericMethod(key.typeArgument));

private static readonly Func<(MethodInfo genericDefinition, Type typeArgument1, Type typeArgument2), MethodInvoker> GenericMethodInvokerFactory2 =
key => MethodInvoker.Create(key.genericDefinition.MakeGenericMethod(key.typeArgument1, key.typeArgument2));
#endif

private static readonly ConcurrentDictionary<(Type, Type), Type> GenericTypeInstances1 = new();

private static readonly ConcurrentDictionary<(Type, Type, Type), Type> GenericTypeInstances2 = new();
Expand Down Expand Up @@ -644,9 +659,17 @@ public static object Activate(this Type type, Type[] genericArguments, params ob
/// The <paramref name="type"/> has no constructors suitable for <paramref name="argumentTypes"/>
/// -or- more than one such constructor.
/// </exception>
#if NET8_0_OR_GREATER
public static ConstructorInvoker GetSingleConstructorInvoker(this Type type, Type[] argumentTypes) =>
ConstructorInfoByTypes.GetOrAdd((type, argumentTypes),
static t => ConstructorExtractor(t) is ConstructorInfo ctor
? ConstructorInvoker.Create(ctor)
: throw new InvalidOperationException(Strings.ExGivenTypeHasNoOrMoreThanOneCtorWithGivenParameters));
#else
public static ConstructorInfo GetSingleConstructor(this Type type, Type[] argumentTypes) =>
ConstructorInfoByTypes.GetOrAdd((type, argumentTypes), ConstructorExtractor)
?? throw new InvalidOperationException(Strings.ExGivenTypeHasNoOrMoreThanOneCtorWithGivenParameters);
#endif

/// <summary>
/// Gets the public constructor of type <paramref name="type"/>
Expand All @@ -659,8 +682,14 @@ public static ConstructorInfo GetSingleConstructor(this Type type, Type[] argume
/// otherwise, <see langword="null"/>.
/// </returns>
[CanBeNull]
#if NET8_0_OR_GREATER
public static ConstructorInvoker GetSingleConstructorInvokerOrDefault(this Type type, Type[] argumentTypes) =>
ConstructorInfoByTypes.GetOrAdd((type, argumentTypes),
static t => ConstructorExtractor(t) is ConstructorInfo ctor ? ConstructorInvoker.Create(ctor) : null);
#else
public static ConstructorInfo GetSingleConstructorOrDefault(this Type type, Type[] argumentTypes) =>
ConstructorInfoByTypes.GetOrAdd((type, argumentTypes), ConstructorExtractor);
#endif

private static readonly Func<(Type, Type[]), ConstructorInfo> ConstructorExtractor = t => {
(var type, var argumentTypes) = t;
Expand All @@ -685,6 +714,7 @@ from pair in zipped
return constructors.SingleOrDefault();
};


/// <summary>
/// Orders the specified <paramref name="types"/> by their inheritance
/// (very base go first).
Expand Down Expand Up @@ -920,6 +950,20 @@ public static MethodInfo CachedMakeGenericMethod(this MethodInfo genericDefiniti
public static MethodInfo CachedMakeGenericMethod(this MethodInfo genericDefinition, Type typeArgument1, Type typeArgument2) =>
GenericMethodInstances2.GetOrAdd((genericDefinition, typeArgument1, typeArgument2), GenericMethodFactory2);

#if NET8_0_OR_GREATER
public static MethodInvoker CachedMakeGenericMethodInvoker(this MethodInfo genericDefinition, Type typeArgument) =>
GenericMethodInvokers1.GetOrAdd((genericDefinition, typeArgument), GenericMethodInvokerFactory1);

public static MethodInvoker CachedMakeGenericMethodInvoker(this MethodInfo genericDefinition, Type typeArgument1, Type typeArgument2) =>
GenericMethodInvokers2.GetOrAdd((genericDefinition, typeArgument1, typeArgument2), GenericMethodInvokerFactory2);
#else
public static MethodInfo CachedMakeGenericMethodInvoker(this MethodInfo genericDefinition, Type typeArgument) =>
CachedMakeGenericMethod(genericDefinition, typeArgument);

public static MethodInfo CachedMakeGenericMethodInvoker(this MethodInfo genericDefinition, Type typeArgument1, Type typeArgument2) =>
CachedMakeGenericMethod(genericDefinition, typeArgument1, typeArgument2);
#endif

public static Type CachedMakeGenericType(this Type genericDefinition, Type typeArgument) =>
GenericTypeInstances1.GetOrAdd((genericDefinition, typeArgument), GenericTypeFactory1);

Expand Down