# Performance of loops (A caching question)

Consider below two C language functions to compute sum of elements in a 2D array. Ignoring the compiler optimizations, which of the two is better implementation of sum?

`// Function 1 ` `int` `fun1(` `int` `arr[R][C]) ` `{ ` ` ` `int` `sum = 0; ` ` ` `for` `(` `int` `i=0; i<R; i++) ` ` ` `for` `(` `int` `j=0; j<C; j++) ` ` ` `sum += arr[i][j]; ` `} ` ` ` `// Function 2 ` `int` `fun2(` `int` `arr[R][C]) ` `{ ` ` ` `int` `sum = 0; ` ` ` `for` `(` `int` `j=0; j<C; j++) ` ` ` `for` `(` `int` `i=0; i<R; i++) ` ` ` `sum += arr[i][j]; ` `} ` |

*chevron_right*

*filter_none*

In C/C++, elements are stored in Row-Major order. So the first implementation has better spatial locality (nearby memory locations are referenced in successive iterations). Therefore, first implementation should always be preferred for iterating multidimensional arrays.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

## Recommended Posts:

- A Time Complexity Question
- Analysis of Algorithms | Set 4 (Analysis of Loops)
- Algorithm Practice Question for Beginners | Set 1
- An interesting time complexity question
- Minimum increment or decrement operations required to make the array sorted
- Sum of numbers in a range [L, R] whose count of divisors is prime
- Minimize the cost of partitioning an array into K groups
- Find next greater element with no consecutive 1 in it's binary representation
- Random list of M non-negative integers whose sum is N
- Count total number of even sum sequences
- Find the sum of prime numbers in the Kth array
- Find numbers which are multiples of first array and factors of second array
- Count all substrings having character K
- Check whether bitwise AND of N numbers is Even or Odd