|
1 | | -using System; |
| 1 | +using MoonSharp.Interpreter.Compatibility; |
| 2 | +using System; |
| 3 | +using System.Collections.Concurrent; |
2 | 4 | using System.Globalization; |
3 | 5 | using System.Linq.Expressions; |
4 | 6 | using System.Reflection; |
5 | | -using MoonSharp.Interpreter.Compatibility; |
6 | 7 |
|
7 | 8 | namespace MoonSharp.Interpreter.Interop.Converters |
8 | 9 | { |
@@ -75,24 +76,39 @@ internal static object DynValueToObject(DynValue value) |
75 | 76 | } |
76 | 77 | } |
77 | 78 |
|
| 79 | + internal static ConcurrentDictionary<(Type BaseType, Type TargetType), MethodInfo> ImplicitConversionCache = |
| 80 | + new ConcurrentDictionary<(Type BaseType, Type TargetType), MethodInfo>(); |
78 | 81 | public static MethodInfo HasImplicitConversion(Type baseType, Type targetType) |
79 | 82 | { |
| 83 | + if (ImplicitConversionCache.TryGetValue((baseType, targetType), out var method)) |
| 84 | + { |
| 85 | + return method; |
| 86 | + } |
| 87 | + |
80 | 88 | try |
81 | 89 | { |
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; |
83 | 93 | } |
84 | 94 | catch |
85 | 95 | { |
86 | 96 | 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; |
89 | 101 | } |
90 | 102 |
|
91 | 103 | if (targetType.BaseType != null) |
92 | 104 | { |
93 | | - return HasImplicitConversion(baseType, targetType.BaseType); |
| 105 | + method = HasImplicitConversion(baseType, targetType.BaseType); |
| 106 | + ImplicitConversionCache.TryAdd((baseType, targetType), method); |
| 107 | + return method; |
94 | 108 | } |
95 | 109 |
|
| 110 | + ImplicitConversionCache.TryAdd((baseType, targetType), null); |
| 111 | + |
96 | 112 | return null; |
97 | 113 | } |
98 | 114 | } |
@@ -397,8 +413,9 @@ private static int GetNumericTypeWeight(Type desiredType) |
397 | 413 | return WEIGHT_NUMBER_DOWNCAST; |
398 | 414 | } |
399 | 415 |
|
400 | | - |
401 | | - |
402 | | - |
| 416 | + public static void ClearCache() |
| 417 | + { |
| 418 | + ImplicitConversionCache.Clear(); |
| 419 | + } |
403 | 420 | } |
404 | 421 | } |
0 commit comments