From 9ada611b90af56a7436b0c7ff725385b0d92a573 Mon Sep 17 00:00:00 2001 From: tangdf Date: Fri, 1 Jun 2018 16:00:51 +0800 Subject: [PATCH] Improve cache performance of MethodFinder.GetAllInstanceMethods --- .../DynamicProxy/Generators/MethodFinder.cs | 31 ++++++------------- .../DynamicProxy/Internal/InvocationHelper.cs | 2 +- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/Castle.Core/DynamicProxy/Generators/MethodFinder.cs b/src/Castle.Core/DynamicProxy/Generators/MethodFinder.cs index 085e907251..85c611f33c 100644 --- a/src/Castle.Core/DynamicProxy/Generators/MethodFinder.cs +++ b/src/Castle.Core/DynamicProxy/Generators/MethodFinder.cs @@ -16,6 +16,7 @@ namespace Castle.DynamicProxy.Generators { using System; using System.Collections.Generic; + using System.Linq; using System.Reflection; /// @@ -24,7 +25,7 @@ namespace Castle.DynamicProxy.Generators /// public class MethodFinder { - private static readonly Dictionary cachedMethodInfosByType = new Dictionary(); + private static readonly Dictionary cachedMethodInfosByType = new Dictionary(); private static readonly object lockObject = new object(); public static MethodInfo[] GetAllInstanceMethods(Type type, BindingFlags flags) @@ -38,16 +39,18 @@ public static MethodInfo[] GetAllInstanceMethods(Type type, BindingFlags flags) lock (lockObject) { - if (!cachedMethodInfosByType.ContainsKey(type)) + if (!cachedMethodInfosByType.TryGetValue(type, out methodsInCache)) { // We always load all instance methods into the cache, we will filter them later + methodsInCache = type.GetMethods( + BindingFlags.Public | BindingFlags.NonPublic + | BindingFlags.Instance) + .Distinct(MethodSignatureComparer.Instance) + .ToArray(); cachedMethodInfosByType.Add( type, - RemoveDuplicates(type.GetMethods( - BindingFlags.Public | BindingFlags.NonPublic - | BindingFlags.Instance))); + methodsInCache); } - methodsInCache = (MethodInfo[])cachedMethodInfosByType[type]; } return MakeFilteredCopy(methodsInCache, flags & (BindingFlags.Public | BindingFlags.NonPublic)); } @@ -76,19 +79,5 @@ private static MethodInfo[] MakeFilteredCopy(MethodInfo[] methodsInCache, Bindin return result.ToArray(); } - private static object RemoveDuplicates(MethodInfo[] infos) - { - var uniqueInfos = new Dictionary(MethodSignatureComparer.Instance); - foreach (var info in infos) - { - if (!uniqueInfos.ContainsKey(info)) - { - uniqueInfos.Add(info, null); - } - } - var result = new MethodInfo[uniqueInfos.Count]; - uniqueInfos.Keys.CopyTo(result, 0); - return result; - } } -} \ No newline at end of file +} diff --git a/src/Castle.Core/DynamicProxy/Internal/InvocationHelper.cs b/src/Castle.Core/DynamicProxy/Internal/InvocationHelper.cs index 65824b7758..ab957cf1e7 100644 --- a/src/Castle.Core/DynamicProxy/Internal/InvocationHelper.cs +++ b/src/Castle.Core/DynamicProxy/Internal/InvocationHelper.cs @@ -158,4 +158,4 @@ public override int GetHashCode() } } } -} \ No newline at end of file +}