Excessive loops of js optimizations take into account performance issues

Source: Internet
Author: User

Suppose we want to generate 10 million random numbers. The general practice is as follows:
Copy codeThe Code is as follows:
Var numbers = [];
For (var I = 0; I <10000000; I ++ ){
Numbers. push (Math. random ());
}

However, when executing this code in IE, a window is displayed prompting you whether to stop the script. In this case, we first think of optimizing the loop body. But obviously, the loop body is very simple and there is no room for optimization. Even if you clear the loop body, the prompt still exists. Therefore, I came to the conclusion that in IE, once the number of loops exceeds a specific value, a prompt is displayed to stop the script.

The reason is found. How can this problem be solved? The first thing I think of is to divide 10 million cycles into several cycles with fewer times. For example, divide it into one hundred times and execute 100,000 cycles each time:
Copy codeThe Code is as follows:
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 cycles is still 10 million. Therefore, we need to separate these one hundred cycles. Although Javascript is single-threaded, you can use setTimeout or setInterval to simulate multithreading. The entire code segment is optimized as follows:
Copy codeThe Code is as follows:
Var numbers = [];
Function begin (){
For (var I = 0; I <100000; I ++ ){
Numbers. push (Math. random ());
}
If (numbers. length <10000000) {// whether it has been completed
SetTimeout (begin, 0 );
} Else {
Alert ("complete ");
}
}
Begin ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.