In a facebook group, I saw a question like :
If a row dominated two dimensional array in the following which one is advantage and why?
a) for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
temp=temp+a[i][j];
b) for(j=0;j<1000;j++)
for(i=0;i<1000;i++)
temp=temp+a[i][j]
From my point I can see there is no difference in the above two statements. And I guess these both are same.
Correct me if am wrong?
There is no difference in theory.
The practical advantage is in cache locality. If you access locations which are far apart, you increase the number of cache misses, which in turn makes the code run slower.
Depending on your processor cache size, you would perhaps need to replace 1000 with some reasonably bigger number in order to perceive the effect.