Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason why is there are several forms of overhead in the foreach version that are not present in the for loop</p> <ul> <li>Use of an IDisposable. </li> <li>An additional method call for every element. Each element must be accessed under the hood by using <code>IEnumerator&lt;T&gt;.Current</code> which is a method call. Because it's on an interface it cannot be inlined. This means N method calls where N is the number of elements in the enumeration. The for loop just uses and indexer</li> <li>In a foreach loop all calls go through an interface. In general this a bit slower than through a concrete type</li> </ul> <p>Please note that the things I listed above are <strong>not</strong> necessarily huge costs. They are typically very small costs that can contribute to a small performance difference. </p> <p>Also note, as Mehrdad pointed out, the compilers and JIT may choose to optimize a foreach loop for certain known data structures such as an array. The end result may just be a for loop. </p> <p>Note: Your performance benchmark in general needs a bit more work to be accurate. </p> <ul> <li>You should use a StopWatch instead of DateTime. It is much more accurate for performance benchmarks. </li> <li>You should perform the test many times not just once</li> <li>You need to do a dummy run on each loop to eliminate the problems that come with JITing a method the first time. This probably isn't an issue when all of the code is in the same method but it doesn't hurt.</li> <li>You need to use more than just 4 values in the list. Try 40,000 instead. </li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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