From 579a81f1418206468b2daae8f6357a763a373a74 Mon Sep 17 00:00:00 2001 From: rauhs Date: Mon, 10 Jul 2023 10:13:33 +0200 Subject: [PATCH] Improve performance for mocking interfaces: Cache GetInterfaceMap Fixes #1350. Revert "Improve performance for mocking interfaces: Cache GetInterfaceMap" This reverts commit 7b8a5a04b5beb97d24ef9ef6e02e6ccd278795db. Improve performance for mocking interfaces: Cache GetInterfaceMap Fixes #1350. --- src/Moq/Extensions.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Moq/Extensions.cs b/src/Moq/Extensions.cs index d975aea48..f01b457b2 100644 --- a/src/Moq/Extensions.cs +++ b/src/Moq/Extensions.cs @@ -2,6 +2,7 @@ // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -155,7 +156,7 @@ public static MethodInfo GetImplementingMethod(this MethodInfo method, Type prox { Debug.Assert(declaringType.IsAssignableFrom(proxyType)); - var map = proxyType.GetInterfaceMap(method.DeclaringType); + var map = GetInterfaceMap(proxyType, method.DeclaringType); var index = Array.IndexOf(map.InterfaceMethods, method); Debug.Assert(index >= 0); return map.TargetMethods[index].GetBaseDefinition(); @@ -427,6 +428,13 @@ static MethodInfo GetInvokeMethodFromUntypedDelegateCallback(Delegate callback) return null; } } + + private static readonly ConcurrentDictionary, InterfaceMapping> mappingsCache = new (); + + private static InterfaceMapping GetInterfaceMap(Type type, Type interfaceType) + { + return mappingsCache.GetOrAdd(Tuple.Create(type, interfaceType), tuple => tuple.Item1.GetInterfaceMap(tuple.Item2)); + } /// /// Visits all constituent parts of , replacing all type matchers