In C#/VB.NET/.NET, which loop runs faster, for
or foreach
?
Ever since I read that a for
loop works faster than a foreach
It will always be close. For an array, sometimes for
is slightly quicker, but foreach
is more expressive, and offers LINQ, etc. In general, stick with foreach
.
Additionally, foreach
may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but it might be quick by foreach
. Actually, the standard LinkedList
doesn't even offer an indexer for this reason.