Usually we iterate through the array in a circular way. But the loop is one of the causes of JS performance problems. In general, we will use the following methods to iterate the array:
Mode 1:
for In loop:
var arr = [1,2,3,4,5];
var obj = {a:1, b:2, c:3};
For (var item in arr|obj) {
fn (item) {
Do sth with Arr[item];
Do sth wtih Obj[item];
};
}
Here's the item:
- The index value of the array, corresponding to the subscript value of arr;
- The key value of object, corresponding to the a,b,c of obj;
Mode 2:
For loop:
for (var i=0; i<arr.length; i++) {
Do sth with Arr[i];
}
Both of these methods should be very common and frequently used. In practice, however, there are performance issues with both approaches.
In mode one, for-in needs to parse out each attribute of the array, which has a high performance overhead. It is very uneconomical to use a known array of keys. So try not to use for-in, unless you don't know what properties to handle, such as JSON objects.
In mode 2, each time the loop is performed, the array length is checked. Reading a property (array length) is slower than reading a local variable, especially if the array contains DOM elements, because each read will scan through the selector related elements on the page, and the speed will be greatly reduced.
So this is where we need to optimize mode 2.
To accelerate:
var arr = [1,2,3,4,5];
var length =arr.length;
for (var i=0; i<length; i++) {
FN (Arr[i]);
}
Now you only need to read the length property of the array once, and the speed has been speeded up. But can it be faster?
The fact is that if the loop termination condition does not perform a comparison operation, the loop can be faster.
Accelerated and Elegant:
var arr = [1,2,3,4,5];
var i = arr.length;
while (i--) {
FN (Arr[i]);
}
Mode 3:
Foreach:
var arr = [1,2,3,4,5];
Arr.foreach (
FN (Value,index) {
do sth with value;
}
)
Attention:
- The two parameters in the foreach callback here are Value,index, which are exactly the opposite of JQuery's $.each;
- ForEach cannot traverse the object;
- IE does not support this method; Firefox and chrome support;
- ForEach cannot use Break,continue to jump out of a loop and use return to skip the loop;
- You can add a second argument to an array, and this in the callback points to the array, and if not added, it points to window;
There are several ways to jump out of a loop:
- return = = End loop and interrupt function execution;
- Break = = End loop function continues execution;
- Continue = = "Skip this cycle;
- For the variable i in the For loop, since ES5 does not exist at the block level scope, it still exists in memory after the end of the loop, so it is recommended to avoid it by using the function self-executing method;
Comparison of several cyclic traversal objects of Cocos JS