Loop interchange

It is often done to ensure that the elements of a multi-dimensional array are accessed in the order in which they are present in memory, improving locality of reference.

For example, in the code fragment: loop interchange would result in: On occasion, such a transformation may create opportunities to further optimize, such as automatic vectorization of the array assignments.

The major purpose of loop interchange is to take advantage of the CPU cache when accessing array elements.

When a processor accesses an array element for the first time, it will retrieve an entire block of data from memory to cache.

In C programming language, array elements in the same row are stored consecutively in memory (a[1,1], a[1,2], a[1,3]) ‒ in row-major order.

Illustration of row- and column-major order