In .NET which loop runs faster for or foreach

Posted by Binoj Antony on Stack Overflow See other posts from Stack Overflow or by Binoj Antony
Published on 2008-12-13T19:45:42Z Indexed on 2010/05/27 13:11 UTC
Read the original article Hit count: 207

Filed under:
|
|
|
|

In c#/VB.NET/.NET which loop runs faster for or foreach?

Ever since I read that for loop works faster than foreach a long time ago I assumed it stood true for all collections, generic collection all arrays etc.

I scoured google and found few articles but most of them are inconclusive (read comments on the articles) and open ended.

What would be ideal is to have each scenarios listed and the best solution for the same

e.g: (just example of how it should be)

  1. for iterating an array of 1000+ strings - for is better than foreach
  2. for iterating over IList (non generic) strings - foreach is better than for

Few references found on the web for the same:

  1. Original grand old article by Emmanuel Schanzer
  2. CodeProject FOREACH Vs. FOR
  3. Blog - To foreach or not to foreach that is the question
  4. asp.net forum - NET 1.1 C# for vs foreach

[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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET