Junior — Middle
Which method — using LINQ or a foreach loop — shows higher performance when processing collections?
sobes.tech AI
Answer from AI
The foreach loop generally shows higher performance compared to using LINQ, especially in speed-critical scenarios. This is because LINQ creates additional objects, uses deferred execution, and can generate intermediate collections, increasing overhead. The foreach loop is a simple iterator without extra abstractions, making it faster.
Example:
var list = Enumerable.Range(1, 1000000).ToList();
// foreach
int sum1 = 0;
foreach(var item in list) {
sum1 += item;
}
// LINQ
int sum2 = list.Sum();
In this case, foreach will be faster, especially if the operations inside the loop are simple. However, LINQ is convenient for declarative code and complex queries where performance is not critical.