Any performance gain when using Any etc on List
Is there any performance gain when using Any开发者_开发问答 extension method than the old for loop way?
In short, no; the performance is likely to be marginally poorer.
In practice, the brevity and clarity of this approach is going to have maintenance benefits over a loop and will be less prone to bugs.
Think of it this way: if you write 50 loops and forget to short-circuit evaluation in one of them, you'd have been better off using .Any
in all 50.
For indexed collections you could the following:
for(int i = 0; i < col.Length;i++)
{
if (predicate(col[i]))
return true;
}
return false;
but for non-indexed IEnumerable<T>
, this is not possible, as it doesn't supply an indexer. This would be the implementation in the framework (via reflection):
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource local in source)
{
if (predicate.Invoke(local))
{
return true;
}
}
return false;
}
As it iterates over all elements of the IEnumerable<T>
, there is no performance gain to be had. However, any "optimization" in this direction would fall under premature optimization, if there is a performance problem, it is more likely to be fixed in your algorithm than in this function.
精彩评论