LINQ to Objects Optimization Methods?

What LINQ to Objects optimization methods do you use or have seen in the wild?

In anticipation of the โ€œyield foreachโ€ and other language / compiler optimizations to arrive in C # in 201x, I am interested in doing my best to use LINQ around the world less than a pain in performance.

One of the patterns I've seen so far is to create custom IEnumerable implementations for specific combinators, so an enumerated number is not re-read several times.

+7
performance optimization linq-to-objects
source share
1 answer

What I noticed several times - do not use:

if (query.Count() > 0) 

... use this instead:

 if (query.Any()) 

Thus, only the first match needs to be found.

EDIT: You may also be interested in a blog I recently wrote about optimizations that may be in LINQ for objects, but are not (or were not in .NET 3.5).

In addition, if you are going to perform many operations x.Contains(y) , and x is the result of an existing query (i.e. it will no longer be some optimized collection), you probably should consider creating a HashSet<T> from x , to avoid linear scanning (query execution to get x results) at each iteration.

+10
source share

All Articles