Originally posted on: http://geekswithblogs.net/abhi/archive/2013/11/21/linq-performace-considerations.aspx
Outside of LINQ statements such as .Any(predicate) and
.First(predicate) short circuiting execution when a matching element is found,
the library does not inherently do any underlying optimizations due to the limits
of what is available to it. Since LINQ only works with IEnumerables, the only
thing that can be done is to loop through the elements in the collection,
therefore, no index access, saving of local properties such as Length, etc. is
possible.
It is important to keep in mind that each time you execute a
LINQ operation, it is likely iterating through your entire collection, even for
simple operations such as .Count() (note: not the same as .Count which is
available on List<T>).
Consolidation of
Expressions
With an understanding of how LINQ works, it is important to
always be on the lookout for the ability to consolidate expressions with more
complex predicates as this will reduce the number of iterations through the
collection.
For Example:
if (collection.Any(predicate)) // 1st Run through
{
var elem = collection.First(predicate); // 2nd Run through
...
}
VS.
var elem = collection.FirstOrDefault(predicate); // Only Run through
if (elem != null)
{
...
}
By consolidating the “Any()” and “First()” in the first
example into the single “FirstOrDefault()”, which takes advantage of the
built-in language features and uses the appropriate LINQ Expression, you have
essentially cut the number of full iterations through the collection in half.
Although this may not always seem beneficial in terms of performance for small
collections, the performance gain can be significant when the collections are
large or when the operation is being run numerous times.