2D Array Traversal: Row-Major vs Column-Major

Question 6 / 12 Correct so far: 0 (0 answered)

Snippet A

Row Major

float sumMatrix(const float mat[][N]) {
    float sum = 0.0f;
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
            sum += mat[i][j];
    return sum;
}

float result = sumMatrix(matrix);
Snippet B

Column Major

float sumMatrix(const float mat[][N]) {
    float sum = 0.0f;
    for (int j = 0; j < N; ++j)
        for (int i = 0; i < N; ++i)
            sum += mat[i][j];
    return sum;
}

float result = sumMatrix(matrix);
Shared test data (shared-setup)
constexpr int N = 1024;
static float matrix[N][N];
struct MatrixInit {
    MatrixInit() {
        for (int i = 0; i < N; ++i)
            for (int j = 0; j < N; ++j)
                matrix[i][j] = static_cast<float>(i * N + j + 1);
    }
} _matrix_init;

Which snippet is faster?

Select the correct answer(s)