I got this question from a c test. I'm very curious about the performance affirmation of the question. I didn't know what to respond. My question is exactly the same. Why performance improved?
Suppose you have the following code which iterates over a large (2000 by 2000) squares 2D array and count the number of non-zero elements in the array. You swap the order of two inner loops so that the x loop is now the y loop. This drastically improved the performance of your code. Why?
int total = 0;
for (int x = 0; x < side_length; x++) {
for (int y = 0; y < side_length; y++) {
if(array[y][x] != 0) {
total += 1;
}
}
}