Roadmap › LINQ — Language Integrated Query › Module: LINQ Internals and EF Core
Lessons in this course (12)

12. Performance and PLINQ

AdvancedMediumLesson 12 of 12
  • LINQ to Objects allocates iterators and delegates: fine for most code, measure in hot paths (tight loops over millions of items may prefer for/Span<T>).
  • .NET 7–9 heavily optimised Sum, Min, Max, Average, Order, Count (vectorised for arrays/spans).
  • Avoid Count() on IEnumerable when you only need "any"; prefer TryGetNonEnumeratedCount.
  • Prefer HashSet.Contains over list.Contains inside a Where (O(1) vs O(n)).
  • PLINQ: source.AsParallel().Where(...).Select(...) uses multiple cores for CPU-bound work on large data; order not preserved unless AsOrdered(); not useful for I/O-bound work or small collections.
csharp
var allowed = new HashSet<int>(allowedIds);
var filtered = items.Where(i => allowed.Contains(i.Id));       // O(n) instead of O(n*m)

var primes = Enumerable.Range(2, 5_000_000).AsParallel().Where(IsPrime).Count();