Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy Does This Improve Performance?
    text
    copied!<p>I've two for loops that basically look up in two different arrays (each having a size around 2-4k at peak) and set a value in a 3rd array based on these values. For some weird reason there is a factor two difference between the performance of this piece of code depending on in which order I put the two for loops.</p> <p>This is the first setup. It executes in ~150 milliseconds on my PC:</p> <pre><code>public static int[] SchoolMultiplication(int[] a, int[] b, int numberBase) { List&lt;double&gt; times = new List&lt;double&gt;(); TimeTest timeTest = new TimeTest(); int aLen = a.Length; int bLen = b.Length; int[,] resultMatrix = new int[a.Length + b.Length, aLen]; int[] result = new int[a.Length + b.Length]; timeTest.Start(); for (int horizontalIndex = 0; horizontalIndex &lt; b.Length; horizontalIndex++) { for (int verticalIndex = 0; verticalIndex &lt; a.Length; verticalIndex++) { resultMatrix[a.Length + b.Length - 1 - verticalIndex - horizontalIndex, verticalIndex] = a[a.Length - verticalIndex - 1] * b[b.Length - horizontalIndex - 1]; } } </code></pre> <p>Now if I change nothing but the order of the loops like this</p> <pre><code>for (int verticalIndex = 0; verticalIndex &lt; a.Length; verticalIndex++) { for (int horizontalIndex = 0; horizontalIndex &lt; b.Length; horizontalIndex++) { resultMatrix[a.Length + b.Length - 1 - verticalIndex - horizontalIndex, verticalIndex] = a[a.Length - verticalIndex - 1] * b[b.Length - horizontalIndex - 1]; } } </code></pre> <p>The total running time of the method drops to about ~400 milliseconds. How does a simple exchange of loop order improve performance by almost 300%? I suppose it is some kind of caching or pointer performance thing?</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