Skip to content

Commit 67c5cf1

Browse files
committed
perf(options): 缓存 GetOptionMappings 结果避免重复计算
- 添加 OptionMappingsCache 静态字典缓存选项映射 - 使用 GetOrAdd 实现线程安全的惰性初始化 - 解决 L-004: GetOptionMappings 方法每次调用都重新计算
1 parent 503459d commit 67c5cf1

1 file changed

Lines changed: 25 additions & 20 deletions

File tree

GameFrameX.Foundation.Options/OptionsBuilder.cs

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ public static TOptions Create<TOptions>(
173173
/// Reflection result cache for caching type property information
174174
/// </summary>
175175
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> PropertyCache = new();
176+
private static readonly ConcurrentDictionary<Type, Dictionary<string, string>> OptionMappingsCache = new();
176177

177178
/// <summary>
178179
/// 获取指定类型的所有属性(带缓存)
@@ -584,36 +585,40 @@ private bool IsBooleanProperty(string key)
584585
}
585586

586587
/// <summary>
587-
/// 获取选项映射
588+
/// 获取选项映射(带缓存)
589+
/// Gets option mappings (with caching)
588590
/// </summary>
589-
/// <returns>选项映射字典</returns>
591+
/// <returns>选项映射字典 / Option mapping dictionary</returns>
590592
private Dictionary<string, string> GetOptionMappings()
591593
{
592-
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
593-
var properties = GetCachedProperties(typeof(T));
594-
595-
foreach (var property in properties)
594+
return OptionMappingsCache.GetOrAdd(typeof(T), _ =>
596595
{
597-
// 处理所有 OptionAttribute 及其派生类
598-
var optionAttrs = property.GetCustomAttributes(typeof(OptionAttribute), true)
599-
.Cast<OptionAttribute>()
600-
.ToList();
596+
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
597+
var properties = GetCachedProperties(typeof(T));
601598

602-
foreach (var optionAttr in optionAttrs)
599+
foreach (var property in properties)
603600
{
604-
// 添加长名称映射
605-
if (!string.IsNullOrEmpty(optionAttr.LongName))
601+
// 处理所有 OptionAttribute 及其派生类
602+
var optionAttrs = property.GetCustomAttributes(typeof(OptionAttribute), true)
603+
.Cast<OptionAttribute>()
604+
.ToList();
605+
606+
foreach (var optionAttr in optionAttrs)
606607
{
607-
result[optionAttr.LongName] = property.Name;
608+
// 添加长名称映射
609+
if (!string.IsNullOrEmpty(optionAttr.LongName))
610+
{
611+
result[optionAttr.LongName] = property.Name;
612+
}
608613
}
609-
}
610614

611-
// 默认使用属性名作为选项名
612-
result[property.Name.ToLowerInvariant()] = property.Name;
613-
result[property.Name.ToLowerInvariant().Replace("_", "-")] = property.Name;
614-
}
615+
// 默认使用属性名作为选项名
616+
result[property.Name.ToLowerInvariant()] = property.Name;
617+
result[property.Name.ToLowerInvariant().Replace("_", "-")] = property.Name;
618+
}
615619

616-
return result;
620+
return result;
621+
});
617622
}
618623

619624
/// <summary>

0 commit comments

Comments
 (0)