Why does the order of the loops affect performance when iterating over a 2D array?

后端 未结 7 694
Happy的楠姐
Happy的楠姐 2020-11-22 06:15

Below are two programs that are almost identical except that I switched the i and j variables around. They both run in different amounts of time. C

7条回答
  •  不思量自难忘°
    2020-11-22 06:46

    The reason is cache-local data access. In the second program you're scanning linearly through memory which benefits from caching and prefetching. Your first program's memory usage pattern is far more spread out and therefore has worse cache behavior.

提交回复
热议问题