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 for mocking interfaces: Cache GetInterfaceMap #1351

Merged
merged 3 commits into from
Aug 16, 2023
Merged
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
10 changes: 9 additions & 1 deletion src/Moq/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -518,6 +519,13 @@ public static Type SubstituteTypeMatchers(this Type type, Type other)
return type;
}

static readonly ConcurrentDictionary<Tuple<Type, Type>, InterfaceMapping> mappingsCache = new();

static InterfaceMapping GetInterfaceMap(Type type, Type interfaceType)
{
return mappingsCache.GetOrAdd(Tuple.Create(type, interfaceType), tuple => tuple.Item1.GetInterfaceMap(tuple.Item2));
}

public static IEnumerable<Mock> FindAllInnerMocks(this SetupCollection setups)
{
return setups.FindAll(setup => !setup.IsConditional)
Expand Down
Loading