I was curious if a 1-Dimensional array is faster than a jagged array, and I measured the performance of the following blocks of code:
Test 1: Jagged Arrays
double[][][][] jagged = ArrayExtensions.Get4DMatrix<double>(100, 100, 50, 50, 0);
for (int iter = 0; iter < 5; iter++)
{
sw.Restart();
for (i = 0; i < 100; i++)
{
for (j = 0; j < 100; j++)
{
for (k = 0; k < 50; k++)
{
for (l = 0; l < 50; l++)
{
test = jagged[i][j][k][l];
jagged[i][j][k][l] = test;
}
}
}
}
Console.WriteLine("Jagged Arrays, Test {0}: {1} ms", iter, sw.ElapsedMilliseconds);
}
Test 2: Single-dimension arrays
double[] single = ArrayExtensions.Get1DArray<double>(25000000);
for (int iter = 0; iter < 5; iter++)
{
sw.Restart();
for (i = 0; i < 100; i++)
{
for (j = 0; j < 100; j++)
{
for (k = 0; k < 50; k++)
{
for (l = 0; l < 50; l++)
{
test = single[i * 100 + j * 100 + k * 50 + l];
single[i * 100 + j * 100 + k * 50 + l] = test;
}
}
}
}
Console.WriteLine("Single Arrays, Test {0}: {1} ms", iter, sw.ElapsedMilliseconds);
}
Running the test yields:
Jagged Arrays, Test 0: 1447 m
Jagged Arrays, Test 1: 1429 m
Jagged Arrays, Test 2: 1431 m
Jagged Arrays, Test 3: 1430 m
Jagged Arrays, Test 4: 1429 m
Single Arrays, Test 0: 386 ms
Single Arrays, Test 1: 387 ms
Single Arrays, Test 2: 386 ms
Single Arrays, Test 3: 387 ms
Single Arrays, Test 4: 387 ms
Also, I ran the tests only with assignment to the array and then only with reading from the array, and the results had the same ratios.
I was expecting that the 1-dimensional arrays were faster than jagged arrays, but I was quite surprised when I saw that the last block executes in only 27% of the execution time of the first.
Could someone explain why this huge difference occurs? Also are there any drawbacks of using 1-dimensional arrays (beside code-readability that it's obviously made harder, and maybe the increased risk of making errors)?
The code was executed in a non-optimized build. In optimized build both tests execute in under 100 ms on each iteration, but I think this has to do more with the code executed inside the loops. Still, 1-dimensional arrays are 50% faster than jagged arrays.