Computational cost of indexing and substitution

Say I have the following code for backsubstitution.

for (int i = n - 1; i >= 0; i--) {
    double temp = b[i];
    if (i != n - 1) {
        for (int j = i + 1; j < n; j++) 
            temp -= A[i][j] * b[j];
    }
    b[i] = temp/A[i][i];
}

But for me as a newbie to programming, the following seems simpler:

for (int i = n - 1; i >= 0; i--) {
    if (i != n - 1) {
        for (int j = i + 1; j < n; j++) 
            b[i] -= A[i][j] * b[j];
    }
    b[i] /= A[i][i];
}

which requires the indexing of b[i] every time it iterates from j = i+1 to j = n - 1. But this b[i] is a fixed quantity since this iteration does not depend on the value of i.

But I'm not sure which one the complier more prefers. Any help?

728x90

1 Answers Computational cost of indexing and substitution

The definition double temp = b[i]; encourages the compiler to keep the tally temp in one of the CPU's registers. With your other code, the compiler might leave the tally in main memory, registers being unsuited to store arrays.

The array would probably be kept in cache unless it were very large, so it would still be fairly fast; but registers are faster.

4 days ago