What LINQ to Objects optimization techniques do you use or have you seen in the wild?
While waiting for "yield foreach" and other language/compiler optimizations to arrive in C# in 201x, I'm interesting in doing everything possible to make using LINQ everywhere less of a performance pain.
One pattern I've seen so far is creating custom IEnumerable implementations for specific combinators such that the enumerable is not being re-enumerated several times.
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.
We can see right away that LINQ is a lot slower than raw SQL, but compiled LINQ is a bit faster. Note that results are in microseconds; real-world queries may take tens or even hundreds of milliseconds, so LINQ overhead will be hardly noticeable.
One that I've spotted a few times - don't use:
if (query.Count() > 0)
... use this instead:
if (query.Any())
That way it only needs to find the first match.
EDIT: You may also be interested in a blog post I recently wrote about optimisations which could be in LINQ to Objects but aren't (or weren't in .NET 3.5).
Additionally, if you're going to do a lot of x.Contains(y)
operations and x
is the result of an existing query (i.e. it's not already going to be some optimised collection), you should probably consider building a HashSet<T>
from x
to avoid a linear scan (performing the query to produce x
's results) on each iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With