Skip to content

Commit

Permalink
Preallocate dictionary size in ToDictionaryWithConflictLog
Browse files Browse the repository at this point in the history
  • Loading branch information
RoosterDragon committed Jan 30, 2022
1 parent a9cd2d4 commit dc15b62
Showing 1 changed file with 3 additions and 4 deletions.
7 changes: 3 additions & 4 deletions OpenRA.Game/Exts.cs
Expand Up @@ -407,7 +407,8 @@ public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)

// Try to build a dictionary and log all duplicates found (if any):
var dupKeys = new Dictionary<TKey, List<string>>();
var d = new Dictionary<TKey, TElement>();
var capacity = source is ICollection<TSource> collection ? collection.Count : 0;
var d = new Dictionary<TKey, TElement>(capacity);
foreach (var item in source)
{
var key = keySelector(item);
Expand All @@ -418,7 +419,7 @@ public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
continue;

// Check for a key conflict:
if (d.ContainsKey(key))
if (!d.TryAdd(key, element))
{
if (!dupKeys.TryGetValue(key, out var dupKeyMessages))
{
Expand All @@ -432,8 +433,6 @@ public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
dupKeyMessages.Add(logValue(element));
continue;
}

d.Add(key, element);
}

// If any duplicates were found, throw a descriptive error
Expand Down

0 comments on commit dc15b62

Please sign in to comment.