|
1 | 1 | using System; |
2 | 2 | using System.Collections; |
| 3 | +using System.Collections.Concurrent; |
3 | 4 | using System.Collections.Generic; |
4 | 5 | using System.Reflection; |
5 | 6 | using System.Text; |
@@ -27,6 +28,23 @@ namespace Singulink.Text |
27 | 28 | /// </remarks> |
28 | 29 | public static class TokenFormatter |
29 | 30 | { |
| 31 | + #region Property Getter Cache |
| 32 | + |
| 33 | + private static readonly ConcurrentDictionary<(Type Type, string PropertyName, bool NonPublic), MethodInfo?> _getterCache = |
| 34 | + new ConcurrentDictionary<(Type, string, bool), MethodInfo?>(); |
| 35 | + |
| 36 | + private static readonly Func<(Type Type, string PropertyName, bool NonPublic), MethodInfo?> _getterFactory = key => { |
| 37 | + var bindingFlags = BindingFlags.Instance | BindingFlags.Public; |
| 38 | + |
| 39 | + if (key.NonPublic) |
| 40 | + bindingFlags |= BindingFlags.NonPublic; |
| 41 | + |
| 42 | + var property = key.Type.GetProperty(key.PropertyName, bindingFlags); |
| 43 | + return property?.GetGetMethod(key.NonPublic); |
| 44 | + }; |
| 45 | + |
| 46 | + #endregion |
| 47 | + |
30 | 48 | /// <summary> |
31 | 49 | /// Substitutes named tokens in the format string with values provided from a dictionary or an object. |
32 | 50 | /// </summary> |
@@ -141,15 +159,10 @@ static bool ResolveTokenSubValue(string tokenKeyName, object currentValue, bool |
141 | 159 | return false; |
142 | 160 | } |
143 | 161 |
|
144 | | - var bindingFlags = BindingFlags.Instance | BindingFlags.Public; |
145 | | - |
146 | | - if (nonPublic) |
147 | | - bindingFlags |= BindingFlags.NonPublic; |
148 | | - |
149 | | - var property = currentValue.GetType().GetProperty(tokenKeyName, bindingFlags); |
| 162 | + var getter = _getterCache.GetOrAdd((currentValue.GetType(), tokenKeyName, nonPublic), _getterFactory); |
150 | 163 |
|
151 | | - if (property?.CanRead == true) { |
152 | | - value = property.GetValue(currentValue); |
| 164 | + if (getter != null) { |
| 165 | + value = getter.Invoke(currentValue, null); |
153 | 166 | return true; |
154 | 167 | } |
155 | 168 |
|
|
0 commit comments