cpp / intermediate
Snippet
Row-Major Cache Locality in 2D Arrays
In C++, multi-dimensional arrays are stored in row-major order. Accessing elements row by row (i then j) is significantly faster than column by column because it utilizes the CPU cache more effectively by accessing contiguous memory addresses.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>const int SIZE = 1000;int main() {int matrix[SIZE][SIZE] = {0};long long total = 0;// Row-major traversal is faster due to spatial localityfor (int i = 0; i < SIZE; ++i) {for (int j = 0; j < SIZE; ++j) {total += matrix[i][j];}}std::cout << "Sum: " << total << std::endl;return 0;}
Breakdown
1
int matrix[SIZE][SIZE] = {0};
Allocates a contiguous block of memory representing a 2D array on the stack.
2
total += matrix[i][j];
Accesses elements in the order they are stored in memory, maximizing cache hits.