Time optimization with too many for loops

Assuming that 10 million random numbers are to be generated, the conventional approach is as follows:

code show as below:

var numbers = [];

for (var i = 0; i < 10000000; i++) {

numbers.push(Math.random());

}

However, when this code is executed under IE, a window pops up to prompt the user whether to stop this script. When this happens, the first thing that comes to mind is to optimize the loop body. But obviously, the body of the loop is simple and leaves little room for optimization. Even if the loop body is emptied, the prompt still exists. So, I came to a conclusion: under IE, once the number of loops exceeds a certain value, a prompt to stop the script will pop up.

The reason is found, how to solve it? My first thought was to divide the 10 million loops into smaller loops. For example, it is divided into 100 times, and each time the loop is executed 100,000 times:

code show as below:

for (var i = 0, j; i < 100; i++) {

for (j = 0; j < 100000; j++) {

......

}

}

IE is not as stupid as we think. It knows that the total number of loops is still 10 million times. Therefore, the one hundred and one hundred thousand loops have to be executed separately. Although Javascript is single-threaded, it is also possible to simulate multi-threading via setTimeout or setInterval. The entire code is optimized as follows:

code show as below:

var numbers = [];

function begin() {

for (var i = 0; i < 100000; i++) {

numbers.push(Math.random());

}

if (numbers.length < 10000000) { // Is it done

setTimeout(begin, 0);

} else {

alert("complete");

}

}

begin();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689772&siteId=291194637