Skip to content

Commit 3a71aa3

Browse files
committed
Add cache for HasImplicitConversion
1 parent e3c2270 commit 3a71aa3

1 file changed

Lines changed: 26 additions & 9 deletions

File tree

MoonSharp.Interpreter/Interop/Converters/ScriptToClrConversions.cs

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
using System;
1+
using MoonSharp.Interpreter.Compatibility;
2+
using System;
3+
using System.Collections.Concurrent;
24
using System.Globalization;
35
using System.Linq.Expressions;
46
using System.Reflection;
5-
using MoonSharp.Interpreter.Compatibility;
67

78
namespace MoonSharp.Interpreter.Interop.Converters
89
{
@@ -75,24 +76,39 @@ internal static object DynValueToObject(DynValue value)
7576
}
7677
}
7778

79+
internal static ConcurrentDictionary<(Type BaseType, Type TargetType), MethodInfo> ImplicitConversionCache =
80+
new ConcurrentDictionary<(Type BaseType, Type TargetType), MethodInfo>();
7881
public static MethodInfo HasImplicitConversion(Type baseType, Type targetType)
7982
{
83+
if (ImplicitConversionCache.TryGetValue((baseType, targetType), out var method))
84+
{
85+
return method;
86+
}
87+
8088
try
8189
{
82-
return Expression.Convert(Expression.Parameter(baseType, null), targetType).Method;
90+
method = Expression.Convert(Expression.Parameter(baseType, null), targetType).Method;
91+
ImplicitConversionCache.TryAdd((baseType, targetType), method);
92+
return method;
8393
}
8494
catch
8595
{
8696
if (baseType.BaseType != null)
87-
{
88-
return HasImplicitConversion(baseType.BaseType, targetType);
97+
{
98+
method = HasImplicitConversion(baseType.BaseType, targetType);
99+
ImplicitConversionCache.TryAdd((baseType, targetType), method);
100+
return method;
89101
}
90102

91103
if (targetType.BaseType != null)
92104
{
93-
return HasImplicitConversion(baseType, targetType.BaseType);
105+
method = HasImplicitConversion(baseType, targetType.BaseType);
106+
ImplicitConversionCache.TryAdd((baseType, targetType), method);
107+
return method;
94108
}
95109

110+
ImplicitConversionCache.TryAdd((baseType, targetType), null);
111+
96112
return null;
97113
}
98114
}
@@ -397,8 +413,9 @@ private static int GetNumericTypeWeight(Type desiredType)
397413
return WEIGHT_NUMBER_DOWNCAST;
398414
}
399415

400-
401-
402-
416+
public static void ClearCache()
417+
{
418+
ImplicitConversionCache.Clear();
419+
}
403420
}
404421
}

0 commit comments

Comments
 (0)