Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your test is not accurate; in the <code>foreach</code> version, you're actually spinning up the enumerator and retrieving each value from the list (even though you aren't using it). In the <code>for</code> version, you aren't doing anything with the list at all, other than looking at its <code>Count</code> property. You're essentially testing the performance of an enumerator traversing a collection compared to incrementing an integer variable an equivalent number of times.</p> <p>To create parity, you'd need to declare a temporary variable and assign it in each iteration of the <code>for</code> loop.</p> <p>That being said, the answer to your question is <em>yes</em>. A copy of the value will be created with every assignment or <code>return</code> statement.</p> <h3>Performance</h3> <p>This pseudocode breakdown should explain why <code>foreach</code> is somewhat slower than using <code>for</code> in this particular instance:</p> <p><code>foreach</code>:</p> <pre><code>try { var en = test.GetEnumerator(); //creates a ListEnumerator T item; while(en.MoveNext()) // MoveNext increments the current index and returns // true if the new index is valid, or false if it's // beyond the end of the list. If it returns true, // it retrieves the value at that index and holds it // in an instance variable { item = en.Current; // Current retrieves the value of the current instance // variable } } finally { } </code></pre> <p><code>for</code>:</p> <pre><code>int index = -1; T item; while(++index &lt; test.Count) { item = test[index]; } </code></pre> <p>As you can see, there's simply less code in the <code>for</code> implementation, and <code>foreach</code> has a layer of abstraction (the enumerator) on top of the <code>for</code>. I wrote the <code>for</code> using a <code>while</code> loop to show the two versions in a similar representation.</p> <h3>With all that said...</h3> <p>You're talking about a trivial difference in execution time. Use the loop that makes the code clearer and smaller, and in this circumstance that looks like <code>foreach</code>.</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