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.
bool hasBig = numbers.Any(n => n > 1000); // stops at the first match int smallest = numbers.Min(); // one pass, no sorting
Try it
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.
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,AllandSinglestop reading as soon as the answer is known (Singlereads one extra element to be sure there is no second match). PreferAny()overCount() > 0; on a lazy sequence the second form walks everything. - Use the size a collection already has.
Count(),ElementAt,LastandToArrayhave fast paths forICollection<T>andIList<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,MinByandMaxByneed 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()orToArray()once. Enumerating a lazy query twice runs the whole pipeline twice (see LINQ pitfalls). - Operators that buffer.
OrderBy,GroupBy,Reverse,Distinct,Join,GroupJoin,Except,IntersectandToLookupread the whole input before returning the first item (some only buffer one side). Lazy operators such asWhere,Select,TakeandSkipstream. - Put filters before expensive steps.
WherebeforeOrderByorSelectshrinks the work of everything after it. - Lambdas that capture variables allocate a closure object. A
staticlambda (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 aList<int>uses an interface-based enumerator, which allocates a boxed struct perforeach. A directforeachover theList<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 needrefaccess, write the loop. LINQ does not work onSpan<T>(a ref struct). Measure first: use a benchmark tool on your own hardware, never guess. - Newer helpers. .NET 9 added
CountBy,AggregateByandIndex, which replace aGroupByfollowed byCountand avoid creating the groups. - Database queries are different. Over
IQueryable<T>, the cost is the SQL the provider generates, not the iterators. See IQueryable.