Neither LINQ nor foreach is always faster. LINQ improves composition, but delegates, iterators, and allocations can matter in a hot loop. foreach is often faster for simple in-memory work; IQueryable LINQ can be far faster because filtering runs in the database.
Example:
decimal total = 0;
foreach (var item in items)
if (item.Active) total += item.Price;
Measure realistic data with BenchmarkDotNet, use Release builds, and consume results so the optimizer cannot remove work. First optimize algorithms, database round trips, and allocations. Choose the clearest implementation unless profiling identifies this code as a bottleneck.
Backbencher Developer · · 0 likes
For simple operations, a plain for or foreach loop is usually somewhat faster and allocates less than LINQ. But in modern .NET the gap is small for most code, and readability often matters more.
Why loops can be faster
- No iterator objects or delegate invocations per element.
- No closures allocated for lambdas that capture variables.
- The JIT can optimise array and span loops very well (bounds-check elimination).
- You can stop early or combine several operations in one pass easily.
Why LINQ can be as fast or faster in some cases
- Modern .NET has heavily optimised LINQ: special iterators for arrays and lists, fused Where().Select() pipelines, and vectorised (SIMD) implementations of Sum, Min, Max and Average for arrays and spans, which can beat a naive loop.
- Methods like Count() and Any() short-circuit or use collection counts.
- LINQ makes it easy to stop early with Any, First or Take, which a careless loop might not do.
Typical benchmark results (conceptually)
- Filtering and summing a large array with a hand-written loop: fastest, zero allocations.
- The same with Where(...).Sum(...): a little slower, with small allocations for the iterator and delegate.
- Chains with OrderBy, GroupBy or ToList: the cost comes mainly from sorting and buffering, which a loop would also have to do.
How to decide
- Business logic, mapping, small or medium collections: LINQ, for clarity and fewer bugs.
- Hot paths (called millions of times), game loops, high-throughput parsing: loops, spans and arrays, ideally after profiling.
- Database queries with EF Core: always LINQ (IQueryable), because it runs in SQL — the database work dominates, not the C# loop.
Measure instead of guessing
[MemoryDiagnoser]
public class SumBenchmarks
{
private readonly int[] _data = Enumerable.Range(0, 1_000_000).ToArray();
[Benchmark] public int Loop() { int s = 0; foreach (var x in _data) if (x % 2 == 0) s += x; return s; }
[Benchmark] public int Linq() => _data.Where(x => x % 2 == 0).Sum();
}
Interview answer: "A loop is generally faster and allocation-free, but LINQ is close in modern .NET and much more readable. I use LINQ by default and switch to loops only when profiling shows a hot spot."