用于迭代二维数组的嵌套循环的哪种排序更有效 [英] Which ordering of nested loops for iterating over a 2D array is more efficient
本文介绍了用于迭代二维数组的嵌套循环的哪种排序更有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下哪种嵌套循环的顺序迭代二维数组在时间(缓存性能)方面更有效?为什么?
Which of the following orderings of nested loops to iterate over a 2D array is more efficient in terms of time (cache performance)? Why?
int a[100][100];
for(i=0; i<100; i++)
{
for(j=0; j<100; j++)
{
a[i][j] = 10;
}
}
或
for(i=0; i<100; i++)
{
for(j=0; j<100; j++)
{
a[j][i] = 10;
}
}
推荐答案
第一种方法稍微好一些,因为分配给的单元格彼此相邻.
The first method is slightly better, as the cells being assigned to lays next to each other.
第一种方法:
[ ][ ][ ][ ][ ] ....
^1st assignment
^2nd assignment
[ ][ ][ ][ ][ ] ....
^101st assignment
第二种方法:
[ ][ ][ ][ ][ ] ....
^1st assignment
^101st assignment
[ ][ ][ ][ ][ ] ....
^2nd assignment
这篇关于用于迭代二维数组的嵌套循环的哪种排序更有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文