preface

Loop is the most resource-consuming operation, and any small loss will be multiplied, thus affecting the efficiency of the overall operation of the program. There are two factors that affect the performance of loops.

  1. What to do with each loop.
  2. The number of cycles.

By reducing the execution time of either or both, you can improve the overall performance of the loop. If this loop takes a long time, it takes even longer to loop multiple times

To optimize the cycle

longhand

// go through the number group method 1
arr=[2.34.65.323.45.34.43.435]
for(var i=0; i<arr.length; i++){console.log(arr[i])
}

2 / / method
var j=0;
while(j<arr.length){
    console.log(arr[j++])
}

3 / / method
var k=0;
do{
    console.log(arr[k++])
}while(k<arr.length)
Copy the code

Optimize the writing

arr = [2.34.65.323.45.34.43.435]

1 / / method
for (var i = 0, len1 = arr.length; i<len; i++) {console.log(arr[i])
}

2 / / method
var j=0,len2=arr.length;
while(j<len2){
    console.log(arr[j++])
}

3 / / method
var k=0,len3=arr.length;
do{
    console.log(arr[k++])
}while(k<len3)
Copy the code

For any loop, the following action occurs each time the body of the loop is executed:

  1. Read the property once in the control condition(arr.length).
  2. Perform a comparison in the control condition(i<arr.length).
  3. judgei<arr.lengthIs the value of the expression zerotrue.
  4. An autoadd operation(i++).
  5. One array lookup(arr[i]).
  6. Primary console outputconsole.log(arr[i]).

The first step in the optimization cycle is to reduce the number of object member and array lookups. On most browsers, these operations take longer than accessing local variables or direct quantities. For example, in the code above, the lookup is done each time the loop is loopedarr.length, which is wasteful because the value does not change during the execution of the loop body, resulting in an unnecessary performance penalty.