Before:

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; } 

After:

  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; } 

There are 2 dictionaries of rights that need to be merged into one. In the first case, when calling the method 500 times. The amount of RAM occupied by the program reaches up to 1GB. In the second case, about 300MB. Why such differences in memory consumption? Indeed, in essence, the methods perform the same thing.

    2 answers 2

    Because you create a new dictionary 500 times in the ToDictionary method:

      Dictionary<TKey, TElement> d = new Dictionary<TKey, TElement>(comparer); foreach (TSource element in source) d.Add(keySelector(element), elementSelector(element)); 
    • Thank you for the answer, in my case it is very much clogged memory - user2455111

    Using Linq in the first case and the lack of Linq in the second. In the first case, the entire sample will be directly unloaded into memory. and in the second as needed ...

    • one
      Using LINQ here is not really what - VladD
    • @VladD Denis may have thought that LinQ spends more memory, maybe it is, but I know for sure that LinQ spends more time, but catastrophically a lot, but spends, but definitely does not take 5 times more memory ... - ParanoidPanda
    • Spending more time? Compared to what? - Artyom Okonechnikov
    • @ArtyomOkonechnikov for example a normal cycle. Write a normal loop and wrap it, for example through a LinQ resharper, and put StopWatch on - ParanoidPanda
    • @ParanoidPanda probably meant that it is not possible to combine 2 dictionary with Linq without using ToDictionary. To ultimately have one Dictionary. Also, when solving this problem, I ran across resentment about the lack of the ability to transfer to the Dictionary constructor the type IEnumerable <KeyValuePair <Key, Value >> - user2455111