Skip to content

Commit

Permalink
Add cache for extension reflecting
Browse files Browse the repository at this point in the history
  • Loading branch information
Marlamin committed Jul 9, 2024
1 parent 0b0942b commit a5903f9
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion Warcraft.NET/Extensions/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
Expand All @@ -7,6 +8,8 @@ namespace Warcraft.NET.Extensions
{
public static class ReflectionExtensions
{
private static ConcurrentDictionary<string, MethodInfo> extensionMethodCache = new();

/// <summary>
/// Get all extension methods by Assembly
/// </summary>
Expand All @@ -27,7 +30,19 @@ where m.GetParameters()[0].ParameterType == type

public static MethodInfo GetExtensionMethod(this Type type, Assembly extensionsAssembly, string name)
{
return type.GetExtensionMethods(extensionsAssembly).FirstOrDefault(m => m.Name == name);
// This is a bit dirty, but it allows us to cache the MethodInfo for future use as reflecting is very expensive.
var uniqueKey = type.ToString() + "-" + extensionsAssembly.ToString() + "-" + name;

if (extensionMethodCache.TryGetValue(uniqueKey, out var cachedMethodInfo))
{
return cachedMethodInfo;
}
else
{
var methodInfo = type.GetExtensionMethods(extensionsAssembly).FirstOrDefault(m => m.Name == name);
extensionMethodCache.TryAdd(uniqueKey, methodInfo);
return methodInfo;
}
}

/// <summary>
Expand Down

0 comments on commit a5903f9

Please sign in to comment.