I've heard it said that "fortran uses column-major ordering because it's faster" but I'm not sure that's true. Certainly, matching column-major data to a column-major implementation will outperform a mixed setup, but I'm curious if there's any absolute reason to prefer row- or column-major ordering. To illustrate the idea, consider the following thought experiment experiment about three of the most common (mathematical) array operations:
Vector-vector inner products
We want to compute the inner product between two equivalent-length vectors, a
and b
:
$$
b = \sum_i a_i x_i.
$$
In this case, both a
and b
are "flat"/one-dimensional and accessed sequentially, so there's really no row- or column-major consideration.
Conclusion: Memory ordering doesn't matter.
Matrix-vector inner products
$$ b_i = \sum_j A_{ij} x_j $$
The naive multiplication algorithm traverses "across" A
and "down" x
. Again, x
is already flat so sequential elements are always adjacent, but adjacent elements in A
's rows are most often accessed together (and I suspect this is likely true for more sophisticated multiplication algorithms like the Strassen or Coppersmith-Winograd algorithms).
Conclusion: Row-major ordering is preferred.
(If you let vectors have transposes you can define a left-multiplication of matrices, $x^T A$, in which case column-major does become preferable, but I think it's conceptually simpler to keep vectors transposeless and define this as $A^T x$.)
Matrix-matrix inner products
$$ B_{ik} = \sum_{j} A_{ij} X_{jk} $$
One more time, the schoolbook algorithm traverses across A
and down X
, so one of those traversals will always be misaligned with the memory layout.
Conclusion: Memory ordering doesn't matter.
Additional consideration: strings & text
ASCII (or similar) strings are most frequently read across-and-down. There's a lot more to consider since a multidimensional array of characters could be ragged (different length rows, e.g. in storing the lines of a book), but the usual traversal pattern at least suggests a preference for row-major ordering.
Conclusion: Row-major ordering is preferred.
Of course, this analysis is extremely crude and theoretical, but it at least suggests row-major ordering is a little more "natural" (from a performance perspective) for multidimensional arrays. Does this stand up to real-world examination? Are there any similar analyses that lean the opposite way and suggest an absolute advantage to column-major ordering?