# javascript – Performance in applications with multiple loops

## Question:

While doing some research, I found several Java codes to calculate the determinant of an array. I passed one of them to javascript and it looked like this:

``````function determinant(A, N) {
var det = 0;
if (N == 1) {
det = A;
} else if (N == 2) {
det = A * A - A * A;
} else {
det = 0;
for (var j1 = 0; j1 < N; j1++) {
var m = [];
for (var k = 0; k < (N - 1); k++) {
m[k] = [];
}
for (var i = 1; i < N; i++) {
var j2 = 0;
for (var j = 0; j < N; j++) {
if (j == j1)  continue;
m[i - 1][j2] = A[i][j];
j2++;
}
}
det += Math.pow(-1.0, 1.0 + j1 + 1.0) * A[j1] * determinant(m, N - 1);
}
}
return det;
}
``````

It's pretty much the same thing. It works and calculates the determinant normally. However, when the matrix passes the order 12×12, both in the front-end and in the back-end, with nodejs, the application takes a long time to calculate the result. When calculates.

I know the reason for this is the multiple loops, as well as being a "recursive" function that runs inside itself over and over again.

However, when testing Math.js to calculate the determinant, regardless of the order of the matrix, be it 30×30, calculates the result in less than 1s. Taking a look at his code for the determinant, I found this:

``````function _det (matrix, rows, cols) {
if (rows == 1) {
return object.clone(matrix);
}else if (rows == 2) {
return subtract(
multiply(matrix, matrix),
multiply(matrix, matrix)
);
}else{
var compute_mu = function (matrix) {
var i, j;
var mu = new Array(matrix.length);
var sum = 0;
for (i = 1; i < matrix.length; i++) {
}
for (i = 0; i < matrix.length; i++) {
mu[i] = new Array(matrix.length);
mu[i][i] = unaryMinus(sum);
for (j = 0; j < i; j++) {
mu[i][j] = 0;
}
for (j = i + 1; j < matrix.length; j++) {
mu[i][j] = matrix[i][j];
}
if (i+1 < matrix.length) {
sum = subtract(sum, matrix[i + 1][i + 1]);
}
}
return mu;
};
var fa = matrix;
for (var i = 0; i < rows - 1; i++) {
fa = multiply(compute_mu(fa), matrix);
}
if (rows % 2 == 0) {
return unaryMinus(fa);
} else {
return fa;
}
}
}
``````

The code isn't much different from some of the other examples I've seen, but how does it manage to have such an incredible performance boost?

Is it some specificity of the code itself? Or the use of various functions external to this block? Or the organization as a whole?

I confess that I was wondering about the performance of this lib, very good by the way. I appreciate any explanation. Thanks in advance.