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 loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc.
I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.
What would be ideal is to have each scenario listed and the best solution for the same.
For example (just an example of how it should be):
- for iterating an array of 1000+
strings -
foris better thanforeach - for iterating over
IList(non generic) strings -foreachis better thanfor
A few references found on the web for the same:
- Original grand old article by Emmanuel Schanzer
- CodeProject FOREACH Vs. FOR
- Blog - To
foreachor not toforeach, that is the question - ASP.NET forum - NET 1.1 C#
forvsforeach
[Edit]
Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter.






foreachinstead offorin C#. If you see answers here that make no sense at all, that is why. Blame the moderator, not the hapless answers. - T.E.D.