前:
private static Dictionary<RuleKey, bool> mergeRules(
Dictionary<RuleKey, bool> topPriorityRules, Dictionary<RuleKey, bool> secondaryRules)
{
var resolvedRules = topPriorityRules.Concat(secondaryRules.Where(kvp => !topPriorityRules.ContainsKey(kvp.Key)))
.ToDictionary(x => x.Key, x => x.Value);
return resolvedRules;
}
后:
private static Dictionary<TKey, TValue> merge<TKey, TValue>(
Dictionary<TKey, TValue> topPriorityRules, Dictionary<TKey, TValue> secondaryRules)
{
var resolvedRules = topPriorityRules;
foreach (var rule in secondaryRules)
if(!resolvedRules.ContainsKey(rule.Key))
resolvedRules.Add(rule.Key, rule.Value);
return resolvedRules;
}
有2个权限集词典需要合并为一个。第一种情况,当方法被调用 500 次时。该程序占用的 RAM 量高达 1GB。在第二种情况下,大约 300MB。为什么内存消耗有这样的差异?毕竟,事实上,这些方法做同样的事情。
因为您在方法中创建了 500 次新字典
ToDictionary:在第一种情况下使用 Linq,在第二种情况下不使用 Linq。在第一种情况下,整个选择将被直接卸载到内存中。在第二个需要时......