In C#/VB.NET/.NET, which loop runs faster,
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):
foris better than
IList(non generic) strings -
foreachis better than
A few references found on the web for the same:
foreachor not to
foreach, that is the question
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.
Patrick Smacchia blogged about this last month, with the following conclusions:
- for loops on List are a bit more than 2 times cheaper than foreach loops on List.
- Looping on array is around 2 times cheaper than looping on List.
- As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).
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 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<T> doesn't even offer an indexer for this reason.