Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For matrix operation, Why is "ikj" faster than "ijk"? [duplicate]

For matrix operation...

ijk-algorithm

public static int[][] ijkAlgorithm(int[][] A, int[][] B) {
    int n = A.length;
    int[][] C = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return C;
}

ikj-algorithm

public static int[][] ikjAlgorithm(int[][] A, int[][] B) {
    int n = A.length;
    int[][] C = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int k = 0; k < n; k++) {
            for (int j = 0; j < n; j++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return C;
}

I know ikj is faster than ijk, but don't know why. Have any simple explanation? Thank you.

like image 227
mpyw Avatar asked Dec 09 '13 09:12

mpyw


1 Answers

In the second snippet, the compiler can optimise

    for (int k = 0; k < n; k++) {
        for (int j = 0; j < n; j++) {
            C[i][j] += A[i][k] * B[k][j];
        }
    }

into something equivalent to

    for (int k = 0; k < n; k++) {
        int temp = A[i][k];  
        for (int j = 0; j < n; j++) {
            C[i][j] += temp * B[k][j];
        }
    }

but no such optimisation can be made in the first snippet. So the second snippet requires fewer lookups into the arrays.

like image 71
Dawood ibn Kareem Avatar answered Sep 18 '22 00:09

Dawood ibn Kareem