Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy in this simple test the speed of method relates to the order of triggering?
    text
    copied!<p>I was doing other experiments until this strange behaviour caught my eye.</p> <p>code is compiled in x64 release.</p> <p>if key in 1, <strong>the 3rd run of List method cost 40% more time than the first 2</strong>. output is </p> <pre><code>List costs 9312 List costs 9289 Array costs 12730 List costs 11950 </code></pre> <p>if key in 2, <strong>the 3rd run of Array method cost 30% more time than the first 2</strong>. output is </p> <pre><code>Array costs 8082 Array costs 8086 List costs 11937 Array costs 12698 </code></pre> <p>You can see the pattern, the complete code is attached following (just compile and run): {the code presented is minimal to run the test. The actually code used to get reliable result is more complicated, I wrapped the method and tested it 100+ times after proper warmed up}</p> <pre><code>class ListArrayLoop { readonly int[] myArray; readonly List&lt;int&gt; myList; readonly int totalSessions; public ListArrayLoop(int loopRange, int totalSessions) { myArray = new int[loopRange]; for (int i = 0; i &lt; myArray.Length; i++) { myArray[i] = i; } myList = myArray.ToList(); this.totalSessions = totalSessions; } public void ArraySum() { var pool = myArray; long sum = 0; for (int j = 0; j &lt; totalSessions; j++) { sum += pool.Sum(); } } public void ListSum() { var pool = myList; long sum = 0; for (int j = 0; j &lt; totalSessions; j++) { sum += pool.Sum(); } } } class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); ListArrayLoop test = new ListArrayLoop(10000, 100000); string input = Console.ReadLine(); if (input == "1") { sw.Start(); test.ListSum(); sw.Stop(); Console.WriteLine("List costs {0}",sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); test.ListSum(); sw.Stop(); Console.WriteLine("List costs {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); test.ArraySum(); sw.Stop(); Console.WriteLine("Array costs {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); test.ListSum(); sw.Stop(); Console.WriteLine("List costs {0}", sw.ElapsedMilliseconds); } else { sw.Start(); test.ArraySum(); sw.Stop(); Console.WriteLine("Array costs {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); test.ArraySum(); sw.Stop(); Console.WriteLine("Array costs {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); test.ListSum(); sw.Stop(); Console.WriteLine("List costs {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); test.ArraySum(); sw.Stop(); Console.WriteLine("Array costs {0}", sw.ElapsedMilliseconds); } Console.ReadKey(); } } </code></pre>
 

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