Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท LINQ

LINQ performance

Reference for LINQ performance in C#: what each operator allocates, which calls are O(1), how to stop early, and when a plain loop or Span is the better choice.

LINQ is fast enough for almost all application code. A query like items.Where(...).Select(...) allocates a few small objects (one iterator per operator, plus delegates if they capture variables) and then walks the data once. The cost only matters on hot paths: tight loops, per-request code that runs millions of times, or queries over very large sequences.

Most LINQ performance work is not about avoiding LINQ. It is about avoiding needless work: stop as soon as you know the answer, never enumerate a sequence twice, never sort when you only need the smallest item, and ask a collection for its Count instead of counting it. This page lists the habits that matter, and the cases where a loop beats a query.

C#
bool hasBig = numbers.Any(n => n > 1000);   // stops at the first match
int smallest = numbers.Min();                // one pass, no sorting

Try it

C# Counting how much work each call does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Collections that already know their size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Usage notes

  • Stop early. Any, First, FirstOrDefault, Take, TakeWhile, Contains, All and Single stop reading as soon as the answer is known (Single reads one extra element to be sure there is no second match). Prefer Any() over Count() > 0; on a lazy sequence the second form walks everything.
  • Use the size a collection already has. Count(), ElementAt, Last and ToArray have fast paths for ICollection<T> and IList<T>. TryGetNonEnumeratedCount (since .NET 6) tells you whether a count is available without enumerating.
  • Do not sort to find one item. OrderBy(...).First() sorts everything: O(n log n) time and O(n) memory. Min, Max, MinBy and MaxBy need one pass and no buffer. To get the top few, OrderBy().Take(k) is smarter than it looks (it uses a partial selection internally), but a heap (PriorityQueue<T,P>) is clearer for large inputs.
  • Materialize once. If you reuse the result of a query, call ToList() or ToArray() once. Enumerating a lazy query twice runs the whole pipeline twice (see LINQ pitfalls).
  • Operators that buffer. OrderBy, GroupBy, Reverse, Distinct, Join, GroupJoin, Except, Intersect and ToLookup read the whole input before returning the first item (some only buffer one side). Lazy operators such as Where, Select, Take and Skip stream.
  • Put filters before expensive steps. Where before OrderBy or Select shrinks the work of everything after it.
  • Lambdas that capture variables allocate a closure object. A static lambda (static n => n * 2) cannot capture and is cached by the compiler. This rarely matters, but it is free to do.
  • Boxing. IEnumerable<int> on a List<int> uses an interface-based enumerator, which allocates a boxed struct per foreach. A direct foreach over the List<int> uses the struct enumerator and allocates nothing.
  • When to use a loop or Span<T>. In inner loops that run millions of times, over arrays or spans, or when you need ref access, write the loop. LINQ does not work on Span<T> (a ref struct). Measure first: use a benchmark tool on your own hardware, never guess.
  • Newer helpers. .NET 9 added CountBy, AggregateBy and Index, which replace a GroupBy followed by Count and avoid creating the groups.
  • Database queries are different. Over IQueryable<T>, the cost is the SQL the provider generates, not the iterators. See IQueryable.