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

后端 未结 7 695
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:59

    Nothing to do with assembly. This is due to cache misses.

    C multidimensional arrays are stored with the last dimension as the fastest. So the first version will miss the cache on every iteration, whereas the second version won't. So the second version should be substantially faster.

    See also: http://en.wikipedia.org/wiki/Loop_interchange.

提交回复
热议问题