Loop Collapsing

Some nested loops can be collapsed into a single-nested loop to reduce loop overhead and improve run-time performance.

Example:

In the code fragment below, the double-nested loop on i and j can be collapsed into a single-nested loop.

int a[100][300];

for (i = 0; i < 300; i++)
  for (j = 0; j < 100; j++)
    a[j][i] = 0;
  

Here is the code fragment after the loop has been collapsed.

int a[100][300];
int *p = &a[0][0];

for (i = 0; i < 30000; i++)
  *p++ = 0;
  

Notes:

Loop collapsing can improve the opportunities for other optimizations, such as loop unrolling.

Loop collapsing is not common in C compilers, but is supported in some C compilers that target the scientific market.