Loop interchange

In compiler theory, loop interchange is the process of exchanging the order of two iteration variables used by a nested loop. The variable used in the inner loop switches to the outer loop, and vice versa. 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:

for j from 0 to 20
  for i from 0 to 10
    a[i,j] = i + j

loop interchange would result in:

for i from 0 to 10
  for j from 0 to 20
    a[i,j] = i + j

On occasion, such a transformation may create opportunities to further optimize, such as automatic vectorization of the array assignments.