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
The differences in speed in a for
- and a foreach
-loop are tiny when you're looping through common structures like arrays, lists, etc, and doing a LINQ
query over the collection is almost always slightly slower, although it's nicer to write! As the other posters said, go for expressiveness rather than a millisecond of extra performance.
What hasn't been said so far is that when a foreach
loop is compiled, it is optimised by the compiler based on the collection it is iterating over. That means that when you're not sure which loop to use, you should use the foreach
loop - it will generate the best loop for you when it gets compiled. It's more readable too.
Another key advantage with the foreach
loop is that if your collection implementation changes (from an int array
to a List
for example) then your foreach
loop won't require any code changes:
foreach (int i in myCollection)
The above is the same no matter what type your collection is, whereas in your for
loop, the following will not build if you changed myCollection
from an array
to a List
:
for (int i = 0; i < myCollection.Length, i++)