C# foreach vs for loop: Which is faster and when to use each
When it comes to iterating over collections in C#, the performance difference between foreach and for loops primarily depends on the collection type being traversed.
For arrays and Lists, a traditional for loop with indexing can be marginally faster because it avoids the overhead of creating an enumerator object, especially in performance-critical scenarios.
The foreach loop internally creates an IEnumerator, which adds a small memory allocation and method call overhead.
However, for most modern applications, this performance difference is negligible and often optimized away by the JIT compiler.
The readability benefits of foreach typically outweigh the minor performance gains of for loops in non-critical code paths.
Collections like LinkedList or those implementing only IEnumerable actually perform better with foreach since they don't support efficient random access.
The rule of thumb: use foreach for readability in most cases, and only switch to for loops when benchmarking shows a meaningful performance improvement in your specific high-performance scenarios.
Example
// Collection to iterate
List<int> numbers = Enumerable.Range(1, 10000).ToList();
// Using for loop
public void ForLoopExample(List<int> items)
{
int sum = 0;
for (int i = 0; i < items.Count; i++)
{
sum += items[i];
}
// For loop can be slightly faster for List<T> and arrays
// because it avoids creating an enumerator
}
// Using foreach loop
public void ForEachLoopExample(List<int> items)
{
int sum = 0;
foreach (int item in items)
{
sum += item;
}
// More readable and works well for any collection type
// Preferred for most scenarios where performance isn't critical
}
// For a LinkedList, foreach is typically faster
public void LinkedListExample(LinkedList<int> linkedItems)
{
int sum = 0;
// This would be inefficient with a for loop since LinkedList
// doesn't support efficient indexing
foreach (int item in linkedItems)
{
sum += item;
}
}