JavaScript for Loop tries to raise high performance _javascript skills

Source: Internet
Author: User
Generally in JavaScript, the array is traversed by using a for loop, as in the following
Copy Code code as follows:

var arr = [];
for (var i=0; i<arr.length; i++) {
Loop
}

The biggest problem with this code is that it gets. Length at every loop, adding to the overhead. So we can improve on that.
Copy Code code as follows:

var arr = [];
For (Var i=0, n=arr.length i<n; i++) {
Loop
}

In this way, first arr.length to the n variable. Gets only once at the start.
But is this going to be a problem? Seems to define a more meaningless variable N. Okay, then keep improving.
Copy Code code as follows:

var arr = [];
for (Var i=arr.length-1 i >-1; i--) {
Loop
}

Okay, so we're going to turn this loop upside down and we'll take that n out and use a constant-1.
If the scenario is applied, it is allowed to not use a for loop. We can use while instead
Good at using both loops to improve javascript efficiency.
Copy Code code as follows:

var arr = [];
var i=arr.length-1;
while (i--) {
Loop Arr[i]
}

Or
Copy Code code as follows:

var arr = [];
var i=arr.length-1;
do {
Loop Arr[i]
}while (I.)

This makes the code simpler and more efficient, especially if you allow the loop body to be executed first, using the do-while effect is obvious.
The only problem is to move I 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.