Note that there are some explanatory texts on larger screens.

plurals
  1. POIn .NET, using "foreach" to iterate an instance of IEnumerable<ValueType> will create a copy? So should I prefer to use "for" instead of "foreach"?
    primarykey
    data
    text
    <p>In .NET, using "foreach" to iterate an instance of IEnumerable will create a copy? So should I prefer to use "for" instead of "foreach"?</p> <p>I wrote some code to testify this:</p> <pre><code>struct ValueTypeWithOneField { private Int64 field1; } struct ValueTypeWithFiveField { private Int64 field1; private Int64 field2; private Int64 field3; private Int64 field4; private Int64 field5; } public class Program { static void Main(string[] args) { Console.WriteLine("one field"); Test&lt;ValueTypeWithOneField&gt;(); Console.WriteLine("-----------"); Console.WriteLine("Five field"); Test&lt;ValueTypeWithFiveField&gt;(); Console.ReadLine(); } static void Test&lt;T&gt;() { var test = new List&lt;T&gt;(); for (int i = 0; i &lt; 5000000; i++) { test.Add(default(T)); } Stopwatch sw = new Stopwatch(); for (int i = 0; i &lt; 5; i++) { sw.Start(); foreach (var item in test) { } sw.Stop(); Console.WriteLine("foreach " + sw.ElapsedMilliseconds); sw.Restart(); for (int j = 0; j &lt; test.Count; j++) { T temp = test[j]; } sw.Stop(); Console.WriteLine("for " + sw.ElapsedMilliseconds); sw.Reset(); } }} </code></pre> <p>And this is the result that I got after I ran the code:</p> <pre><code> one field foreach 68 for 72 foreach 68 for 72 foreach 67 for 72 foreach 64 for 73 foreach 68 for 72 ----------- Five field foreach 272 for 193 foreach 273 for 191 foreach 272 for 190 foreach 271 for 190 foreach 275 for 188 </code></pre> <p>As we can see in the result, "foreach" always takes more time than "for". </p> <p>So should I prefer to use "for" instead of "foreach" when iterating through a generic collection of value type?</p> <p><strong>Note: thanks for the reminder, I edited the code and result. but still, foreach is running slower than for.</strong></p>
    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.
 

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