3

The default way of using for loops which is taught in most cases looks something like this:

for (int x = 0; x < 32; x++)
{
    for (int y = 0; y < 32; y++)
    {
        level[x][y].update();
    }
}

But some people insist that swapping the x and y order in the for loop increases performance. I suspect that this is because of cache misses?

for (int y = 0; y < 32; y++)
{
    for (int x = 0; x < 32; x++)
    {
        level[x][y].update();
    }
}

Can anybody explain if this is correct and if so, WHY does it help? If not, what is the reason?

Markall
  • 173
  • 7
  • 1
    I think the swap can only decrease performance on catch, since `level[x][0]` and `level[x][1]` are closer than `level[0][x]` and `level[1][x]` – apple apple Mar 30 '18 at 08:28
  • Does this remarkable Q&A answer your question? https://stackoverflow.com/questions/16699247/what-is-cache-friendly-code/16699282#16699282 – YSC Mar 30 '18 at 08:30
  • This is a classic example for cache miss. I'm wondering why you see the code without explanation. – llllllllll Mar 30 '18 at 08:32
  • `level[x][y]` is somewhat unusual (array-of-columns layout) and then you *would* want the y-loop to be the inner most loop. – harold Mar 30 '18 at 10:23

0 Answers0