Checked LINQ queries and collections for inefficiencies.

- Made Array.IndexOf available via extension method.
- Made ToHashSet extension method.
- Change collections queried often via Contains into sets.
- Avoid Count() extension if Count or Length property exist.
- Made Count() > 0 checks and variations calls to Any() instead.
- Don't call ToList/ToArray if there is no benefit to materializing the sequence.
- If the sequence does benefit from materialization, follow this general pattern:
  - Collection queried often via Contains use ToHashSet to speed up lookups.
  - Short lived variables use ToList. This is because ToArray requires an extra copy to output the final size.
  - Collections persisted into fields or for a long time use ToArray to minimize memory overhead.
This commit is contained in:
RoosterDragon
2014-05-23 19:52:44 +01:00
committed by RoosterDragon
parent f5f3747338
commit 82bea961ba
44 changed files with 151 additions and 126 deletions

View File

@@ -106,6 +106,11 @@ namespace OpenRA
return ret;
}
public static int IndexOf<T>(this T[] array, T value)
{
return Array.IndexOf(array, value);
}
public static T Random<T>(this IEnumerable<T> ts, MersenneTwister r)
{
var xs = ts as ICollection<T>;
@@ -299,6 +304,11 @@ namespace OpenRA
return ts.Concat(moreTs);
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
public static Dictionary<TKey, TSource> ToDictionaryWithConflictLog<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, string debugName, Func<TKey, string> logKey, Func<TSource, string> logValue)
{
return ToDictionaryWithConflictLog(source, keySelector, x => x, debugName, logKey, logValue);
@@ -341,7 +351,7 @@ namespace OpenRA
// If any duplicates were found, throw a descriptive error
if (dupKeys.Count > 0)
{
var badKeysFormatted = string.Join(", ", dupKeys.Select(p => "{0}: [{1}]".F(logKey(p.Key), string.Join(",", p.Value.ToArray()))).ToArray());
var badKeysFormatted = string.Join(", ", dupKeys.Select(p => "{0}: [{1}]".F(logKey(p.Key), string.Join(",", p.Value))));
var msg = "{0}, duplicate values found for the following keys: {1}".F(debugName, badKeysFormatted);
throw new ArgumentException(msg);
}