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.
This is the first setup. It executes in ~150 milliseconds on my PC:
public static int[] SchoolMultiplication(int[] a, int[] b, int numberBase)
{
List<double> times = new List<double>();
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 < b.Length; horizontalIndex++)
{
for (int verticalIndex = 0; verticalIndex < a.Length; verticalIndex++)
{
resultMatrix[a.Length + b.Length - 1 - verticalIndex - horizontalIndex, verticalIndex] = a[a.Length - verticalIndex - 1] * b[b.Length - horizontalIndex - 1];
}
}
Now if I change nothing but the order of the loops like this
for (int verticalIndex = 0; verticalIndex < a.Length; verticalIndex++)
{
for (int horizontalIndex = 0; horizontalIndex < b.Length; horizontalIndex++)
{
resultMatrix[a.Length + b.Length - 1 - verticalIndex - horizontalIndex, verticalIndex] = a[a.Length - verticalIndex - 1] * b[b.Length - horizontalIndex - 1];
}
}
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?