Javascript for loop to improve performance

Source: Internet
Author: User

The for loop is generally used to traverse arrays in javascript, as shown below:
Copy codeThe Code is as follows:
Var arr = [];
For (var I = 0; I <arr. length; I ++ ){
// Loop
}

The biggest problem with this kind of code is that the. length is obtained through the. Operator in each loop, increasing the overhead. So we can improve it in this way.
Copy codeThe Code is as follows:
Var arr = [];
For (var I = 0, n = arr. length; I <n; I ++ ){
// Loop
}

In this way, the arr. length is saved to the n variable first. It is obtained only once at the beginning.
But is that okay? It seems that n is a meaningless variable. Okay. continue to improve.
Copy codeThe Code is as follows:
Var arr = [];
For (var I = arr. length-1; I>-1; I --){
// Loop
}

In this case, we reverse the loop order and remove the n and use a constant-1.
If the for loop is not allowed in the Application Scenario. We can use while instead
Be good at using these two loop statements to improve javascript efficiency.
Copy codeThe Code is as follows:
Var arr = [];
Var I = arr. length-1;
While (I --){
// Loop arr [I]
}

Or
Copy codeThe Code is as follows:
Var arr = [];
Var I = arr. length-1;
Do {
// Loop arr [I]
} While (-- I)

In this way, the code is more concise and more efficient, especially if you can execute a loop body first, the use of do while is very effective.
The only problem is that I is moved out of the loop.

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.