Note that there are some explanatory texts on larger screens.

plurals
  1. POIn .NET, which loop runs faster, 'for' or 'foreach'?
    text
    copied!<p>In C#/VB.NET/.NET, which loop runs faster, <code>for</code> or <code>foreach</code>?</p> <p>Ever since I read that a <code>for</code> loop works faster than a <code>foreach</code> loop a <a href="http://msdn.microsoft.com/en-us/library/ms973839.aspx" rel="noreferrer">long time ago</a> I assumed it stood true for all collections, generic collections, all arrays, etc.</p> <p>I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.</p> <p>What would be ideal is to have each scenario listed and the best solution for the same.</p> <p>For example (just an example of how it should be):</p> <ol> <li>for iterating an array of 1000+ strings - <code>for</code> is better than <code>foreach</code></li> <li>for iterating over <code>IList</code> (non generic) strings - <code>foreach</code> is better than <code>for</code></li> </ol> <p>A few references found on the web for the same: </p> <ol> <li><a href="http://msdn.microsoft.com/en-us/library/ms973839.aspx" rel="noreferrer">Original grand old article by Emmanuel Schanzer</a></li> <li><a href="http://www.codeproject.com/KB/cs/foreach.aspx" rel="noreferrer">CodeProject FOREACH Vs. FOR</a></li> <li><a href="http://blogs.msdn.com/kevin_ransom/archive/2004/04/19/116072.aspx" rel="noreferrer">Blog - To <code>foreach</code> or not to <code>foreach</code>, that is the question</a></li> <li><a href="http://weblogs.asp.net/mdavey/archive/2004/02/25/79504.aspx" rel="noreferrer">ASP.NET forum - NET 1.1 C# <code>for</code> vs <code>foreach</code></a></li> </ol> <p> </p> <p>[Edit]</p> <p>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. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload