Home > Web Front-end > JS Tutorial > body text

js optimizes loops with too many times taking into account performance issues

高洛峰
Release: 2017-02-04 13:18:53
Original
1319 people have browsed it

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

var numbers = []; 
for (var i = 0; i < 10000000; i++) { 
  numbers.push(Math.random()); 
}
Copy after login

However, when executing this code under IE, a window pops up prompting the user whether to stop this script. When this happens, the first thing that comes to mind is optimizing the loop body. But obviously, the loop body is very simple and there is no room for optimization. Even if the loop body is cleared, 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 has been found, how to solve it? My first thought was to divide the 10 million loops into several smaller loops. For example, divide it into one hundred times, and execute one hundred thousand loops each time:

for (var i = 0, j; i < 100; i++) { 
  for (j = 0; j < 100000; j++) { 
    ...... 
  } 
}
Copy after login

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

var numbers = []; 
function begin() { 
  for (var i = 0; i < 100000; i++) { 
    numbers.push(Math.random()); 
  } 
  if (numbers.length < 10000000) { // 是否已完成 
    setTimeout(begin, 0); 
  } else { 
    alert("complete"); 
  } 
} 
begin();
Copy after login

More js optimization loops with too many times. Considering performance issues, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template