0

I recently came across this example while reading some introduction to C text. There was no explanation to why the codes below are different when it comes to cache friendliness, and I can't figure out the difference. The text goes like this:

Comparing these two codes:

// cache-friendly
int i, j;
for (i = 0; i < 10; ++i)
{
    for (j = 0; j < 20; ++j)
    {
        a[i][j] += 10;
    }
}

VS

// not cache-friendly
int i, j;
for (j = 0; j < 20; ++j)
{
    for (i = 0; i < 10; ++i)
    {
        a[i][j] += 10;
    }
}

Does anybody see why code A is cache-friendly compared to code B?

harogaston
  • 124
  • 1
  • 10
  • 1
    It is about the locality of the data you're looking at. A 2D array is a contiguous block of memory, and it is accessed in row-major form. So the elements in a single row are contiguous, the elements in a column are separate. – juanchopanza Sep 25 '14 at 21:50
  • Your processor instruction cache can predict sequencial array access better than something it considers random. – Pieter21 Sep 25 '14 at 21:53
  • @juanchopanza Thank you, that clarifies everything. If you would like to post that as an answer I will take it. – harogaston Sep 25 '14 at 21:57
  • (Despite having marked it as a duplicate) In your case the array is so small it will comfortably fit in L1 cache, so it shouldn't cause a significant difference. – Oliver Charlesworth Sep 25 '14 at 21:57
  • @OliverCharlesworth I know in this case the are no practical differences, but my question was more conceptually oriented. In any case, I already looked at the question you pointed as mine being a duplicate of, thank you. – harogaston Sep 25 '14 at 22:00

0 Answers0