patterncsharpCritical
In .NET, which loop runs faster, 'for' or 'foreach'?
Viewed 0 times
netrunsfasterforloopforeachwhich
Problem
In
Ever since I read that a
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):
strings -
than
A few references found on the web for the same:
[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.
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
arrayof 1000+
strings -
for is better than foreach- for iterating over
IList(non generic) strings -foreachis better
than
forA 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.
Solution
Patrick Smacchia blogged about this last month, with the following conclusions:
loops on
than looping on
(which I believe, is what we all do).
forloops onListare a bit more than 2 times cheaper thanforeach
loops on
List.- Looping on array is around 2 times cheaper than looping on
List.
- As a consequence, looping on array using
foris 5 times cheaper
than looping on
List using foreach(which I believe, is what we all do).
Context
Stack Overflow Q#365615, score: 462
Revisions (0)
No revisions yet.