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

后端 未结 7 773
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

    This line the culprit :

    x[j][i]=i+j;
    

    The second version uses continuous memory thus will be substantially faster.

    I tried with

    x[50000][50000];
    

    and the time of execution is 13s for version1 versus 0.6s for version2.

提交回复
热议问题