Why Julia arrays are stored in column-major order?
Column-major vs row-major are not entirely symmetric regarding code style, because when we access the
i,j'th element of an array, we write
A[i,j] with the row index first, which can break the symmetry.
For example, I find it surprising that in:
[(println(i, " ", j); (i,j)) for i=1:5, j=1:5]
i is traversed faster than
j, even though it looks like
j is an inner loop.
This is completely different from a true nested for loop:
for i=1:5, j=1:5 println(i, " ", j) end
j is indeed varying faster. If Arrays were row-major, these two code snippets would vary
j faster, which looks more consistent to me given that in both cases the iteration is specified by
for i=1:5, j=1:5.
Another example is:
[(println(i, " ", j); (i,j)) for i=1:5 for j=1:5]
j varies faster, which makes
[... for i=1:5, j=1:5] different from
for i=1:5 for j=1:5. The difference is not just that the later is linearized, but also the order in which elements are traversed. Again, there would be no difference in order if arrays were row major.
I’m just wondering about the reasoning behind the column-major choice, and if there is a more “natural” way to think about this that I am missing.
Probably this has been discussed before on Github, though I can’t find it now.