Is it possible to design a compiler which optimizes a loop in which arrays are accessed in alternate fashion? For example like this:
// int[] a,b
int sum = 0;
for(int i = 0; i < n; i++)
{
sum += a[i] + b[i];
}
With the usual sequential array storage, a[i]
and b[i]
may be far away from each other in memory. Therefore, I think a good compiler optimization would detect that a[i]
and b[i]
are always accesses at the "same" time, and store the arrays interleaved, that is a[0] b[0] a[1] b[1] ...
so that one memory access may retrieve both a[i]
and b[i]
.
a[i]
andb[i]
be retrieved with one memory operation, but that they were located nearby in memory for better cache performance. $\endgroup$ – Dave Clarke Sep 6 '12 at 15:52